如何修改ggplot2图例键?

Phi*_*tte 2 r legend ggplot2

有没有办法用 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.
    )
  )
Run Code Online (Sandbox Code Playgroud)

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

che*_*123 5

虽然@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()
  )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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