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")