控件 ggplot2图例查看而不影响绘图

我正在使用 ggplot2绘制线条,如下所示:

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

current plot.

我发现传奇标记很小,所以我希望它们更大。如果我改变大小,情节上的线条也会改变:

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

thick plot lines.

但我只想看到传说中的粗线条,我希望情节上的线条是细的。我尝试使用 legend.key.size,但它改变了标记的正方形,而不是线的宽度:

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

我还试图用积分表示:

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

但是当然它仍然影响着情节和传说:

points

我想用线条表示情节,用点/点表示图例。

所以我想问两件事:

  1. 如何在不改变绘图的情况下改变图例中线条的宽度?
  2. 如何在情节中画线,但在图例中画点/点/方块?
37382 次浏览

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