【问题标题】:Change the vertical spacing of one legend in ggplot?更改ggplot中一个图例的垂直间距?
【发布时间】:2020-08-31 19:25:22
【问题描述】:

我在 ggplot2 中使用如下代码绘制两组数据,这导致我有两个图例(忽略丑陋的情节,这只是一个示例)

x <- ggplot(mtcars)+
  theme_bw() +
    theme(legend.position=c(0.8, 0.8), legend.direction="horizontal", 
          legend.key.size=unit(0.008, "cm"), legend.title=element_blank(), 
          legend.margin=margin(), legend.spacing = unit(0.04, "cm")) +
    guides(colour = guide_legend(override.aes = list(size=6)), shape= guide_legend(override.aes = list(size=5))) +
    geom_point(aes(x=mpg, y=cyl, colour=cyl))+
    geom_point(aes(x=mpg, y = hp, shape=as.factor(carb)))

print(x)

问题是对我来说,底部的黑色形状在垂直方向上靠得太近了,我希望两排黑色形状之间有更多的垂直空间。我尝试使用 legend.spacing.y 但它根本没有帮助,它只改变了两个单独的图例之间的空间(用于 cyl 和 carb)。我想知道是否有一些主题命令可以让我执行类似 legend.spacing(legend=carb, unit(0.1, "cm")) 的操作,因此它专门作用于 carb 图例。

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以在guide_legend 中使用keyheight 参数

    ggplot(mtcars) +
      theme_bw() +
      theme(
        legend.position = c(0.8, 0.8),
        legend.direction = "horizontal",
        legend.key.size = unit(0.008, "cm"),
        legend.title = element_blank(),
        legend.margin = margin(),
        legend.spacing = unit(0.04, "cm")
      ) +
      guides(colour = guide_legend(override.aes = list(size = 6)),
             shape = guide_legend(override.aes = list(size = 5), keyheight = 2)) +
      geom_point(aes(x = mpg, y = cyl, colour = cyl)) +
      geom_point(aes(x = mpg, y = hp, shape = as.factor(carb)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 2015-03-19
      • 1970-01-01
      相关资源
      最近更新 更多