【问题标题】:change size/order of one guide in combined ggplot guide在组合 ggplot 指南中更改一个指南的大小/顺序
【发布时间】:2023-04-06 10:07:01
【问题描述】:

我发现形状和线型的组合图例难以解读。具体来说,因为它在线条后面而且太小,所以很难看到形状。

library(ggplot2)
ggplot(mtcars)+
geom_point(aes(x=hp,y=mpg,shape=as.factor(cyl)))+
geom_smooth(aes(x=hp,y=mpg,linetype=as.factor(cyl)),method='lm')+
theme_bw(base_size=18)

如何在不增加线条大小的情况下增加图例中形状的大小?

下面的这种尝试增加了两者的大小(不是我想要的)。 guide_legend 的顺序似乎也不会影响图例键中符号的顺序。更改 geom_point 和 geom_smooth 的顺序会在图例中给出所需的结果,但不会在图中给出。

+guides(linetype=guide_legend('Cylinders'),shape=guide_legend('Cylinders',override.aes=list(size=3)))

我还希望theme(legend.key.size=grid::unit(2,'cm')) 会扩大图例键中对象的大小,但它似乎没有这样做。

建议? 也欢迎其他想法如何使图表更清晰。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

图例按绘制顺序生成线和点,因此为了获得线前的点,您可以这样做:

ggplot(mtcars)+
  geom_smooth(aes(x=hp,y=mpg,linetype=as.factor(cyl)),method='lm')+
  geom_point(aes(x=hp,y=mpg,shape=as.factor(cyl)))+
  theme_bw(base_size=18)

更改图例中点的大小有点令人沮丧。也许您想尝试一种技巧,让您从一个情节中取出一个传奇并将其放在另一个情节上:

library(gtable)
library(gridExtra)

# Has the legend you want
p1 <- ggplot(mtcars)+
  geom_smooth(aes(x=hp,y=mpg,linetype=as.factor(cyl)),method='lm')+
  geom_point(aes(x=hp,y=mpg,shape=as.factor(cyl)),size=3)+
  theme_bw(base_size=18)+labs(shape="Cylinders",linetype="Cylinders")

# Has the plot you want
p2 <- ggplot(mtcars)+
  geom_smooth(aes(x=hp,y=mpg,linetype=as.factor(cyl)),method='lm')+
  geom_point(aes(x=hp,y=mpg,shape=as.factor(cyl)))+
  theme_bw(base_size=18)+theme(legend.position="none")

# Take the legend from p1
fill.legend <- gtable_filter(ggplot_gtable(ggplot_build(p1)), "guide-box") 
legGrob <- grobTree(fill.legend)

# Put the legend from p1 onto p2
grid.arrange(p2, legGrob, ncol=2, widths = c(6,1))

【讨论】:

  • 我真的不想要情节线前面的点(正如我在问题中指出的那样),但我会在最后接受你对黑客的回答。
  • 你可以用线后面的点来制作你想要的情节,用前面的点来制作你想要的图例。这就是黑客的魅力。
猜你喜欢
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
相关资源
最近更新 更多