如何控制 ggplot2 图例中包含的几何图形?

How can I control the geometry that is included in ggplot2 legends?

我想知道如何修改图例中出现的几何图形。

这是我的例子:

stockmlp %>%
  ggplot(aes(y = RMSE, x = Depth, color = Depth)) +
  geom_boxplot(alpha = 0) +
  geom_point(size = 10, alpha = 0.5) +
  facet_wrap(~Stock, scales="free_y")

geom_boxplot with geom_point

我认为 guides(color = guide_legend(override.aes = list( ))) 可能有用,但我不知道该在列表中添加什么。

我想从颜色图例中删除箱线图框架,以便它只显示一个彩色圆圈。

您无法使用 guides 功能更改图例中显示的 geoms,您只能更改其外观(例如标题、美学...)。

这里的一个选项是通过不在主 ggplot 调用中指定它而仅在 geom_point 调用中指定它来仅将 color 美学应用于点,但这会导致不着色的箱线图:

stockmlp %>%
  ggplot(aes(y = RMSE, x = Depth)) +
  geom_boxplot(alpha = 0) +
  geom_point(size = 10, alpha = 0.5, aes(color = Depth)) +
  facet_wrap(~Stock, scales="free_y")

更好的选择是指定不在 geom 调用中显示图例:

stockmlp %>%
  ggplot(aes(y = RMSE, x = Depth, color = Depth)) +
  geom_boxplot(alpha = 0, show.legend = F) +
  geom_point(size = 10, alpha = 0.5) +
  facet_wrap(~Stock, scales="free_y")

要删除图例后面的灰色背景,您可以使用以下方法:

+ theme(legend.key = element_blank())

左侧已删除,右侧为默认值: