Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping extra white space in a plot made using ggplot package in R

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,

enter image description here

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,

enter image description here

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

like image 372
Amm Avatar asked Feb 21 '26 20:02

Amm


1 Answers

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

like image 130
Amm Avatar answered Feb 24 '26 08:02

Amm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!