首页 文章

在不影响绘图的情况下控制ggplot2图例

提问于
浏览
64

我正在用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 回答

  • 97

    要仅在图例中更改线宽,您应使用函数 guides() ,然后使用 colour= 使用 guide_legend()override.aes= 并设置 size= . 这将覆盖绘图中使用的大小,并将仅为图例使用新的大小值 .

    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

    要获得图例中的点数和绘图变换中的线条,可以添加 geom_point(size=0) 以确保点不可见,然后在 guides() 设置 linetype=0 以删除线条和 size=3 以获得更大的点数 .

    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

相关问题