【问题标题】:How to modify ggplot2 legend keys?如何修改 ggplot2 图例键?
【发布时间】:2020-07-23 12:26:14
【问题描述】:

有没有办法用ggplot2改变图例中键的宽度和高度?在以下示例中,我想将图例中的点替换为可以调整宽度和高度的矩形。我尝试使用keywidth 没有成功。

library(ggplot2)

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(
    legend.position = "top",
    legend.title = element_blank()
  ) +
  guides(
    color = guide_legend(
      label.position = "top",
      override.aes = list(shape = 15, size = 5),
      keywidth = unit(2, "cm") # This is not giving me what I was expecting.
    )
  )

reprex package (v0.3.0) 于 2020 年 7 月 23 日创建

【问题讨论】:

  • 而不是图表方块中的点,你想要吗?
  • 我想在图中使用点(这已经可以了),但在图例中使用矩形。目前,我能得到的最接近的是使用正方形(形状 = 15)。

标签: r ggplot2 legend


【解决方案1】:

虽然@Ian 的回答有效,但还有一种更简单的方法,即在geom_point() 调用中定义要使用的图例键字形。需要注意的重要一点是,如果我们指定关键字形应该是一个矩形,我们需要提供填充美感(或者您将只为字形提供空矩形):

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(aes(fill=Species), key_glyph='rect') +
  theme(
    legend.position = "top",
    legend.title = element_blank()
  )

您应该能够通过 guides()theme() 更改从那里调整关键尺寸以满足您的需求。

【讨论】:

    【解决方案2】:

    使用来自 baptiste 的 this answer 的灵感,一种方法可能是将 GeomPoint$draw_key 函数替换为 GeomBar$draw_key

    GeomPoint$draw_key <- GeomBar$draw_key
    ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
      geom_point() +
      scale_fill_identity() +
      theme(
        legend.position = "top",
        legend.title = element_blank()
      ) +
      guides(
        color = guide_legend(
          label.position = "top",
          keywidth = unit(2, "cm")
        )
      )
    
    

    【讨论】:

      【解决方案3】:

      作为参考,我发布解决方案。

      library(ggplot2)
      
      ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, fill = Species)) +
        geom_point(key_glyph = "rect") +
        theme(
          legend.position = "top",
          legend.title = element_blank()
        ) +
        guides(
          color = guide_legend(
            label.position = "top",
            keywidth = unit(2, "cm"), # This is not giving me what I was expecting.
          )
        )
      

      reprex package (v0.3.0) 于 2020-07-23 创建

      【讨论】:

        猜你喜欢
        • 2016-06-23
        • 2012-08-21
        • 1970-01-01
        • 2023-03-12
        • 2013-03-05
        • 2020-05-01
        • 1970-01-01
        • 2011-11-11
        • 2014-06-21
        相关资源
        最近更新 更多