Cropping extra white space in a plot made using ggplot package in R
For preserving the size of the legend list while changing the number of legend columns to 2 this following code works. It is necessary to have ncol=2
within parentheses of override.aes
for the legend size to be preserved.
+ guides(colour = guide_legend(override.aes = list(size=4),ncol=2))
For completely removing the whitespace surrounding the plot made using ggplot in R this code does the job,
+theme(plot.margin=unit(c(0,0,0,0),"mm"))
Make sure to include library(grid)
package
Amm
Updated on June 04, 2022Comments
-
Amm almost 2 years
I would like to crop the extra whitespace which results after plotting a plot in ggplot.
I have the following piece of code,
p1 <- ggplot(d2, aes_string(x=names(sameTLM_df)[1],y= "value")) + geom_point(aes(color = variable), size = 1)+ theme_bw()+ theme(legend.text=element_text(size=18), legend.title=element_text(size=18))+ theme(axis.text=element_text(size=20)) + theme(axis.title=element_text(size=24,face="bold")) + scale_color_discrete(name = "Title", labels = c("1","2","3","4","5","6","7","8","9")) + labs(x = "x", y = "y")+ guides(colour = guide_legend(override.aes = list(size=4)))
which produces a plot like this,
I would like to crop the white background surrounding the plot and change the number of columns in legend to 2, so I use to the following code,
p2 <- p1 + guides(col = guide_legend(ncol = 2)) + theme(plot.background = element_rect(fill = NULL))
Which results in a plot such as this,
However the "whitespace" (I have made the background color yellow to illustrate the space between the boundary and plot) is not removed and while the number of columns is changed to 2, the size of the legend list changes as well, which I don't need. Could someone please guide me how to preserve the size of the legend list while changing the columns to 2 and removing the extra white space in the outer bounds of the plot.
Thanks
-
Jordan over 7 yearsFYI, if you are making a clean, tight version that doesn't have any labels on the axis and you want the margins to hug the plot, in addition to making the axis.text and axis.ticks set to element_blank() you also need to set the labs(x=NULL,y=NULL) instead of labs(x="",y="").