Control ggplot2 legend look without affecting the plot

RPlotGgplot2Legend

R Problem Overview


I'm plotting lines with ggplot2 like this:

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

current plot.

I find legend marks to be small so I want them to be bigger. If I change the size, lines on the plot change too:

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

thick plot lines.

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

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 to use points:

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

But of course it still affects both plot and legend:

points

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

So I'm asking about two things:

  1. How to change width of line in the legend without changing the plot?
  2. How to draw lines in the plot, but draw points/dots/squares in the legend?

R Solutions


Solution 1 - R

To change line width only in the legend you should use function guides() and then for colour= use guide_legend() with override.aes= and set size=. This will override size used in plot and will use new size value just for 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 legend and lines in plot workaround would be add geom_point(size=0) to ensure that points are invisible and then in guides() set linetype=0 to remove lines and size=3 to get larger 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbaltazarView Question on Stackoverflow
Solution 1 - RDidzis ElfertsView Answer on Stackoverflow