Control the appearance of ggplot2 without affecting the plot

I draw lines with ggplot2 as follows:

ggplot(iris, aes(Petal.Width,Petal.Length,color=Species)) + geom_line() + theme_bw() 

current plot .

I believe that legend labels are small, so I want them to be larger. If I change the size, the lines in the plot also change:

 ggplot(iris, aes(Petal.Width,Petal.Length,color=Species)) + geom_line(size=4) + theme_bw() 

thick plot lines .

But I want to see only thick lines in the legend, I want the lines on the plot to be thin. I tried using legend.key.size , but it changes the square of the label, not the line width:

 library(grid) # for unit ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw() + theme(legend.key.size=unit(1,"cm")) 

big legend keys

I also tried using dots:

 ggplot(iris,aes(Petal.Width,Petal.Length,color=Species)) + geom_line() + geom_point(size=4) + theme_bw() 

But, of course, this still affects both the plot and the legend:

points

I wanted to use lines for the plot and dots / dots for the legend.

So, I ask about two things:

  • How to change the line width in a legend without changing the graph?
  • How to draw lines in a plot, but draw dots / dots / squares in a legend?
+61
r plot ggplot2 legend
May 03 '13 at 9:48
source share
1 answer

To change the line width only in the legend, you must use the guides() function, and then for colour= use guide_legend() with override.aes= and set size= . This will override the size used in the plot, and will use the new size value only for the legend.

 ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+ guides(colour = guide_legend(override.aes = list(size=3))) 

enter image description here

To get points in the legend and lines in the geom_point(size=0) , add geom_point(size=0) to make sure the points are invisible, and then set linetype=0 in guides() to remove lines and size=3 to get big points.

 ggplot(iris,aes(Petal.Width,Petal.Length,color=Species))+geom_line()+theme_bw()+ geom_point(size=0)+ guides(colour = guide_legend(override.aes = list(size=3,linetype=0))) 

enter image description here

+92
May 03 '13 at 9:56
source share



All Articles