【问题标题】:Spacing between the legend keys for multiple legends in ggplot2 in RR中ggplot2中多个图例的图例键之间的间距
【发布时间】:2019-11-17 21:37:35
【问题描述】:

我在互联网上进行了搜索,但找不到解决问题的方法。

所以为了更可靠地说,我们有一个带有两个图例的图表,如下所示:

library(ggplot2)

ggplot() + 
  geom_point(data = mtcars, aes(x = disp, y = mpg, color = gear), 
             pch =20, size=18) + 
  geom_line(data = mtcars, aes(x = disp, y = mpg, size = disp/mpg*100)) +
  scale_size(range = c(0,3.5)) +
  guides(size = guide_legend("", order = 1, keywidth = 2, keyheight = 1.5), 
         color = guide_legend("", order = 2, keywidth = 1, keyheight = 1 )) +
  labs(x = "disp", y = "mpg") +
  geom_text(size=2.7, color = "grey29",  vjust=-0.8) +
  theme_bw() 

# ggsave("trial.png", width = 11.5, height = 8.5)

我可以通过使用更改与大小相关的第一个图例组的间距 size 中的guides 选项。但是,对于表示颜色的第二组,我既不能使整个组更靠近图形,也不能缩小到彩色圆圈之间的大小。

我也尝试过主题中的图例选项,例如legend.spacing.x/ylegend.key.width/height。这些选项仅适用于第一个图例组。

有没有办法减少不同颜色键之间的尺寸?更改键的大小也很容易发现。

为了使我的要求更清楚,以下是我要调整的差距:

提前致谢。

【问题讨论】:

    标签: r ggplot2 legend legend-properties


    【解决方案1】:

    我不确定您需要什么,但我认为您希望图例中的点更小。在这种情况下,override.aes() 就是您需要的函数。

    如果您的问题不同,请进一步说明,以便我们为您提供帮助。

    library(ggplot2)
    
    ggplot() + 
      geom_point(data = mtcars, aes(x = disp, y = mpg, color = gear), 
                 pch =20, size=18) + 
      geom_line(data = mtcars, aes(x = disp, y = mpg, size = disp/mpg*100)) +
      scale_size(range = c(0,3.5)) +
      guides(size = guide_legend("", order = 1, keywidth = 2, keyheight = 1.5), 
             color = guide_legend("", order = 2, keywidth = 1, keyheight = 1, 
                                  override.aes = list(size=9))) +
      labs(x = "disp", y = "mpg") +
      geom_text(size=2.7, color = "grey29",  vjust=-0.8) +
      theme_bw()
    

    reprex package (v0.3.0) 于 2019 年 7 月 8 日创建

    【讨论】:

    • 谢谢,这使图例键更好看。但是,我试图让图例关键框(在这些图中,它们应该是透明的,但无论如何它们都在那里)更接近实际的图边界(框架)和/或减少第二个图例中彩色圆圈之间的间隙。我将在帖子中添加另一个情节,并标记我希望在一分钟内更改的地方。
    【解决方案2】:

    图例间距始终是一个问题,并获得很多选票e.g. here。 我认为您的特定示例中的问题之一可能是gear 的连续性。因式分解可能会有所帮助(如果您的值多于gear,请改用cut()),然后使用unit() 更改guides 调用中的图例间距。我已经稍微简化了您的代码,并将title = '' 替换为title = NULL,否则ggplot 实际上正在绘制一个空对象。

    library(tidyverse)
    
    mtcars_f <- mtcars %>% mutate(gear_f = factor(gear)) #factorising gear
    
    ggplot(mtcars_f, aes(disp, mpg)) + 
      geom_point(aes(color = gear_f), size = 10) + 
      geom_line(aes(size = disp/mpg*100)) +
      guides(size = guide_legend(title = NULL, order = 1, 
             keyheight = unit(0.1, 'inch')), 
             color = guide_legend(title = NULL, order = 2, 
             keyheight = unit(0.1, 'inch'))) +
      scale_color_brewer(palette = 'Blues') +
      theme(legend.key= element_blank())
    

    reprex package (v0.3.0) 于 2019 年 7 月 19 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多