控制ggplot2图例外观而不影响绘图 [英] Control ggplot2 legend look without affecting the plot
问题描述
我正在用 ggplot2 绘制线条,如下所示:
I'm plotting lines with ggplot2 like this:
ggplot(iris, aes(Petal.Width,Petal.Length,color=Species)) + geom_line() + theme_bw()
.
我发现图例标记很小,所以我希望它们更大.如果我改变大小,图上的线条也会改变:
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()
.
但我只想在图例中看到粗线,我希望情节上的线很细.我尝试使用 legend.key.size
但它改变了标记的平方,而不是线的宽度:
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"))
我也尝试使用积分:
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:
我想用线条表示情节,用点/点表示图例.
I wanted to use lines for the plot and dots/points for the legend.
所以我要问两件事:
- 如何在不改变情节的情况下改变图例中的线宽?
- 如何在图中画线,而在图例中画点/点/正方形?
推荐答案
要仅在图例中更改线宽,您应该使用函数 guides()
然后用于 colour=
使用 guide_legend()
和 override.aes=
并设置 size=
.这将覆盖绘图中使用的大小,并将仅对图例使用新的大小值.
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)))
要在图例中获取点和绘图解决方法中的线将添加 geom_point(size=0)
以确保点不可见,然后在 guides()
中设置 linetype=0
删除线和 size=3
以获得更大的点.
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)))
这篇关于控制ggplot2图例外观而不影响绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!