Making SVG plots in R; why the need for X11? - linux

I've been looking around for an answer for this. I seem to gather that some sort of X11 (or a virtual frame buffer) is always required for plotting.
However I do not understand why that is needed for SVG graphics, seems like I should even be able to create them manually, so why does R seem to always need the X11?
I imagine that the X11 performs some functionality, like selecting colors from a palette or something like that. Is that the case? if not, how can I avoid the X11 completely.
I'm using ggplot2 to make a plot and gridSVG to extract it as in:
plot <- ggplot(data=data, aes(...)) + ...
print(plot)
mysvg <- grid.export()

Related

Custom drawing rotated SVG to Leaflet map

I am using leaflet 1.7.1 and I need to put custom markers on map.
I am currently using circles (as in: L.circle([lat, lon], {radius: rad}).addTo(map);) as my markers (note radius is significant and should be in meters).
Now I need to add a "direction" to this circle essentially displaying something like:
I actually need to implement some L.directedCircle([lat, lon], {radius: rad, heading=45}).addTo(map);, but I don't know how to do that.
I also tried looking for plugins, but nothing seems to do what I need.
Note that the image above is just an example, I'm open to other options but that seems very simple (it's just a 4-points SVG poliline) and effective.
If that matters I'm using leaflet through pyqtlet2, but I'm prepared to "get my hands dirty" using directly javascript.
Any help appreciated.

How to read a map into octave

This is a follow up to my post three weeks ago here How do I use m_map in octave, without really being a nuissance to kind and busy people. My problem is simply how does one overlay a basemap on an octave contour plot. After interpolating my irregularly spaced data (works for both contour lines and filled contours) I plot with the code:
contour(xi, yi, obsi, cstart:cstep:cend)
colorbar;
xlabel('Longitude'),ylabel('Latitude')
title('Mean Rain Onset')
saveas(gcf,'rainzam.pdf')
And I get
I have downloaded several map formats: ne_50m_admin_0_countries.zip, the apparently obsolete m_map (with associated tbase.Z, gshhg-bin-2.3.2.zip), soa.7z, world-bounds.7z, gshhg-gmt-2.3.2.tar.gz, dcw-gmt-1.1.1.tar.gz.
My question is has anyone used any of these maps in octave or gnuplot, and how to? I would appreciate any assistance.
Basically you have to load those maps in octave, they represent borders or coastlines with two variables (x,y) which you can then add to your plot with
hold on
plot(x,y)
That's the easy part, the hard part is to load the maps. All of them have different formats, which means it is a completely different story how to load them. For instance, the ne_50m_admin_0_countries.zip has a dbf format. Either you convert it first to ascii text and load it easily with the load function of octave or you need the OI package (http://wiki.octave.org/IO_package), which in turn demands java (http://wiki.octave.org/Java_package). I don't think this is the easy way for a newbie, so I suggest to convert the maps individually to text: google for "convert dbf to csv", "convert dbf to text", "convert dbf to ascii", etc... Perhaps some of those maps can be even loaded with excel and then saved as text (csv), the important issue is to convert them to text!
If you want to draw physical coastlines, you may download them from this link
https://www.naturalearthdata.com/downloads/
Then, after the drawing of a contour map of your own datas, you may add the coastlines using the following commands:
pkg load mapping
hold on
h = shapedraw ('FileName.shp','r','linewidth',1)

Set legend text's HorizontalAlignment to left in octave

I have legend text that in matlab behaves as
set(gcf,'DefaulttextHorizontalAlignment','left');
now I am attempting to replicate this in octave, but for some reason octave seems to ignore the above command.
I am using cygwin Xwin octave and GNUPlot.
(I am not trying to move the text to the other-side of the "line" legend('left'))
Doing some tests, it turns out that I can set the property, but it isn't affecting anything.
LegendHandle = legend( phvec, legendvec, 'Location', 'NorthEastOutside' );
legtxt=findobj(LegendHandle,'type','text');
get(legtxt(1),'HorizontalAlignment') %% returns left
It seems Gnuplot supports the option to change the legend horizontal alignment, but Octave doesn't provide the access to this function in Gnuplot (although it works with FLTK). You simply can't do anything about it, except filing a feature request on the Octave tracker.
Source: http://octave.1599824.n4.nabble.com/set-horizontalalignment-for-legend-text-td2218246.html
So yes, there's currently no solution to left align the legend text using gnuplot, the only thing you can do to remove this awful blank space is, as you said, to use legend('left') to swap the text to the left of the symbols.
I can replicate your problem but only if using gnuplot. It works with other graphics toolkits.
While gnuplot was Octave's default graphics toolkit for a long time, the Octave developers have been slowly replacing it with their own alternative in order to avoid its limitations. I believe recent versions of Octave will already default to fltk but you can change it yourself:
octave-cli-3.8.1> graphics_toolkit fltk
octave-cli-3.8.1> graphics_toolkit # confirm
ans = fltk
octave-cli-3.8.1> x = 0:0.1:10;
octave-cli-3.8.1> figure;
octave-cli-3.8.1> plot (x, [sin(x); cos(x)]);
octave-cli-3.8.1> legend ("long sin", "cos", "Location", "NorthEastOutside");

Create Editable plots from R

I'm creating a series of plots in R (I'm using ggplot2, but that's not essential) and I want to be able to save my output so I can then edit it for furthur use, For instance, I might want to move legends about, or adjust colours etc. I have seen that ggplot2 has a save command but that seems to produce pdf's or bitmaps, neither of which are particularly editable
How do other people do this ? Any good ideas ?
Here's some sample code to produce a sample plot;
library(ggplot2)
dataframe<-data.frame(fac=factor(c(1:4)),data1=rnorm(400,100,sd=15))
dataframe$data2<-dataframe$data1*c(0.25,0.5,0.75,1)
dataframe
testplot<-qplot(x=fac, y=data2,data=dataframe, colour=fac, geom=c("boxplot", "jitter"))
testplot
Thanks
Paul.
Other editable formats:
Take a look at help(devices) for other formats which are available: these include svg, pictex and xfig, all of which are editable to greater or lesser extents.
Note that PDFs can be edited, for instance using the Omnigraffle tool available for Apple's OSX.
Other ways to record plot data:
In addition, you can record R's commands to the graphics subsystem for repeating it later - take a look at dev.copy:
Most devices (including all screen devices) have a display list
which records all of the graphics operations that occur in the
device. 'dev.copy' copies graphics contents by copying the display
list from one device to another device. Also, automatic redrawing
of graphics contents following the resizing of a device depends on
the contents of the display list.
Using Rscript to create a repeatable, editable plot:
I typically take a third strategy, which is to copy my R session into an Rscript file, which I can run repeatedly and tweak the plotting commands until it does what I want:
#!/usr/bin/Rscript
x = 1:10
pdf("myplot.pdf", height=0, width=0, paper="a4")
plot(x)
dev.off();
With ggplot and lattice, you can use save to save the plot object to disk and then load it later and modify it. For example:
save(testplot, file = "test-plot.rdata")
# Time passes and you start a new R session
load("test-plot.rdata")
testplot + opts(legend.position = "none")
testplot + geom_point()
Thanks for the answers, I've played around with this, and after some help from my friend Google I found the Cairo package, which allows creation of svg files, I can then edit these in Inkscape.
library(Cairo)
Cairo(600,600,file="testplot.svg",type="svg",bg="transparent",pointsize=8, units="px",dpi=400)
testplot
dev.off()
Cairo(1200,1200,file="testplot12200.png",type="png",bg="transparent",pointsize=12, units="px",dpi=200)
testplot
dev.off()
Now I just have to play around with the various settings to get my plot as good as it can be before writing the file.
right click the mouse on the output plot
Copy as metafile
then save plot into a word document (right click to edit picture to covert to the plot to Microsoft Office drawing Object)

Alternatives to using text() to adding text to a plot

This may be a naive question, but I was wondering if there's a better way than using text() to adding text to a plot. Note, I'm also using layout() as well. Specifically, I have a section of a plot where I would like to add some text with headings followed by regular text.
text() is fine it seems for simple annotations, but to get the spacing right for several lines of text seems to require a lot of manual manipulation of the x and y and cex parameters. Any suggestions?
Here are some alternative options to consider:
- the gplots package has a textplot function to add some text output in a base graphics plot.
- plotrix has a function addtable2plot
- for grid graphics grid.text() is available and in gridExtra there is a function grid.table() (see, e.g., R-Wiki)
If you're using base graphics, then text() is probably your best bet, and fiddling with coordinates etc is part of the game. If you want to learn a new framework, the lattice package is a reworking of the basic approach to plotting in R. It be installed by default so help(package='lattice') will get you started.
Here's a pretty good guide (pdf) to graphics in general in R, with a substantial section on lattice:
download

Resources