Saving ggplot as SVG ruins quality - r

I have a plot generated from the following code:
bars <- ggplot(plottingFrame, aes(x=X, y=as.factor(Y))) +
geom_raster(aes(fill=colour)) + scale_fill_identity())
Where plottingFrame is a load of colour values precomputed. geom_raster is used with scale_fill_identity to make a "heatmap" of different colours:
Ignore the squashed axis and cutoff titles, I made the image smaller so it's not too big.
The above image is what happens when ggsave is used on the bars object and it is saved as a png.
When I try to use ggsave to save as svg however, it blurs the colours between the three coloured rows.
Why does saving a geom_raster based plot blur the three rows - Seq1, Seq2, and Seq3, when png keeps them distinct as in the above image? And how can I stop saving to sag blurring them?
Thanks,
Ben W.

Related

ggplot2: Is there a way to eliminate distortions of shapes when using geom_point and position_dodge?

I am making plots that have categorical x variables with multiple factors for each category. I use geom_point and position_dodge similar to this post: ggplot2: geom_point() dodge shape but NOT color. If you look closely at the plot created in that post you can see that when xVar=C the "+" points are not symetrical, in that the right and bottom lines are longer than the top and left. Perhaps this is not a big deal for simple plots, but I have a fairly complex plot. I have a 3*3 multi-plot using grid_arrange. This multi-plot has a total of 81 points and error bars for each of the points. The distorted points are not centered on many of the error bars, so this problem really stands out in my case. Perhaps this has something to do with using position_dodge with grid_arrange.
I've tried exporting the image as different file types (e.g., jpg, png, pdf).
Here is some code from the aforementioned link:
x=tibble(Color=c(rep('A',12),rep('B',12),rep('C',12)),
Shape=rep(c(rep('A',3),rep('B',3),rep('C',3),rep('D',3)),3),
xVar=rep(c('A','B','C'),12),
Value=rnorm(36))
ggplot(x,aes(xVar,Value,color=Color,shape=Shape))+
geom_point(position=position_dodge(width=.5))
ggplot(x,aes(xVar,Value,color=Color,shape=Shape,group=Shape))+
geom_point(position=position_dodge(width=.5))
I would like to have geom_point shapes that are not distorted.

r - how to set plot size regardless of legend width ggplot2

I'm looping through a spatial feature dataframe and creating hundreds of maps from each column using ggplot2. Depending on the data present in the column, the legend for each map may be a different size, making the plot size different for each map. Although subtle, you can see below that the first map is offset to the left relative to the second map because of the longer label in the legend
I'd like to maintain the size of the plot area (in this case, the map area) so that all the saved maps are consistently sized and lined up when flipping through them. I've looked through questions and answers on here, but all I've been able to find are solutions for how to preserve aspect/ratio of different plots on the same image/document as described here. I'd like to be able to save each map as its own file.
Can anyone give me suggestions about how to keep the plot size consistent regardless of legend width when saving these plots as images using ggplot2?

Save Filled Area of Polygon in R

I am plotting polygon in R and saving it.Problem, I am facing is that the whole plot is saved as png file but I want to save only the filled area in the polygon.
Is there a way for that ?
x<-c(0.000000000,0.010986328,0.006351471,-0.004634857)
y<-c(0.000000000,0.007232612,0.012841203,0.006199415)
file_name = paste("~/Downloads/Plot", ".png", sep="")
png(file_name,width=1280,height = 720,units="px",res=200)
plot(x,y,axes=FALSE,ylab='',xlab='')+polygon(x,y,col="#FF0000FF")
dev.off()
If you're drawing a monofigure plot (which is the default), then I believe there are three possible sources of spacing that can cause a plot element to not extend to the edges of the graphics device:
1: data coordinate limits that are larger than the extent of the plot element.
2: "internal spacing", which is best thought of as an expansion of the plot area that sits inside the margins.
3: margins. This is normally where axes, ticks, tick labels, axis labels, titles, and sometimes legends are drawn.
All of these sources of spacing can be eliminated with the following customizations:
1: set the xlim and ylim graphics parameters to perfectly fit the target plot element.
2: set xaxs='i',yaxs='i', which can be done with either a preemptive par() call or on the initial plot() call.
3: zero the margins with mar=c(0,0,0,0). This must be done with par() prior to the initial plot() call.
Example:
## generate data
pts <- data.frame(x=c(0.2,0.4,0.9,0.7),y=c(0.5,0.4,0.5,0.6));
## precompute plot parameters
xlim <- range(pts$x);
ylim <- range(pts$y);
## draw plot
par(mar=c(0,0,0,0));
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,ann=F);
points(pts$x,pts$y,pch=21L);
polygon(pts$x,pts$y,col='red',pch=21L);
Multifigure plots can incur one additional source of spacing, namely outer margins, but it looks like that doesn't concern you for this problem. In any case, I'm pretty sure outer margins always default to zero anyway.
See par() for the relevant documentation.
It looks like I misunderstood the question. What you want is a transparent background, which is different from simply fitting the image size to the plot element.
You can use the png() function to set the background to be transparent by passing bg='transparent', as explained on the documentation page.
For example, here's my fitted image saved with a transparent background:
Note that not all image viewers will correctly detect and/or clearly depict the transparency of the background. I would highly recommend GIMP, which is basically a free Photoshop knockoff, albeit markedly lighter in features. GIMP depicts transparent regions as a kind of checkerboard of grey squares, which looks like this:

Set Legend Spacing in ggplot2

I am trying to create a plot in R using ggplot2. The figure looks great when displayed in R, but when I write it to pdf the labels in the legend slightly overlap the different color lines they are defining. How do I add white space between entries so that this does not happen?
Without code example it is hard to say, but if you don't see this problem in the R display and you see it in the pdf, you can try to increase the pdf output size. When rendering a pdf, the font size is kept and the elements of the graph are more squeezed if the output size is smaller than the displayed one.
p<-ggplot(mpg,aes(cyl,year))+geom_point()
ggsave('yourfile.pdf',p,width=10,height=10) # default is 7 on my install
I don't know if it is possible to change the spacing, but I don't see any parameters for that in the theme() or element_text() documentation

Reducing legend size in ggplot beyond default size

My goal is to make several plots with ggplot and combine them into a single plot using grid.arrange in the gridExtra package.
I'm having an issue in that the legends in my ggplot (while appropriately sized for a single plot) are too large when I try to place the plots side by side with grid.arrange. The resulting combined plots reduce the x-axis but keep the legend original size. So the result is a very skinny plot, next to an needlessly large legend. So I'd like to reduce the size of the legend in each plot, enough so that I can place my plots side by side. Or possible shrink them enough to bring them inside the actual plot without being to overbearing.
V1<-rnorm(10)
V2<-rnorm(10)
V3<-rnorm(10)
DF<-data.frame(V1,V2,V3)
ggplot(DF,aes(x=V1,y=V2,size=V3))+
geom_point(fill='red',shape=21)+
theme_bw()+
scale_size(range=c(5,20))
This plot command produces a standard legend size to the right of the plot.
I've tried using different theme elements:
+theme(legend.key.size = unit(0.5, "cm")
or
+theme(legend.key.width=unit(0.3,"cm"),legend.key.height=unit(0.3,"cm"),legend.position = c(0.7, 0.8))
And while I can make the legend larger using these theme commands, I can't make the legend any smaller than the default legend. So is there any way to shrink the legend beyond the default size?
I can also change the default size of my pdf device to make it wider and accommodate the large legends , but I'd like to work with a standard pdf size for now.
The whole point of a legend is to map aesthetics on the plot (e.g., color, fill, shape, or size) to levels identified in the legend. The parameters legend.key.size, .width, and .height adjust the size of the box surrounding the legend element. With color, fill, and shape you can make the legend items as small as you like, but with size, the size of the element tells you which bubble(s) correspond to which legend item, so the legend items must have sizes that correspond to what is on the plot.
Here are three possibilities that might help you:
Option 1: Put the legend inside the plot.
ggplot(DF,aes(x=V1,y=V2,size=V3))+
geom_point(fill='red',shape=21)+
theme_bw()+
scale_size(range=c(5,20))+
theme(legend.justification=c(1,0), legend.position=c(1,0))
Option 2: Use facet_wrap(...) if you can. This way you only get one legend for the set of plots.
Option 3: Use color and size, and then hide the size legend altogether.
ggplot(DF,aes(x=V1,y=V2,size=V3, color=V3))+
geom_point(shape=19)+
theme_bw()+
scale_size(range=c(5,20), guide="none")+
scale_color_gradient(high="#ff0000", low="#ffffcc")

Resources