改变ggplot2图例中中位数和均值的颜色

Posted

技术标签:

【中文标题】改变ggplot2图例中中位数和均值的颜色【英文标题】:Changing the colour of median and mean in ggplot2 legend 【发布时间】:2021-05-27 03:37:13 【问题描述】:

请忽略整个图表上的随机点 - 这只是一个快速可重复的示例来说明我的意思:

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, fill = Species)) + 
  geom_violin(alpha = 0.5) +
  stat_summary(aes(shape="mean",group=1),fun = "mean",
               size = 2, geom = "point", color = "black") +
  stat_summary(aes(shape = "median", group = 2), fun = "median",
               size = 2, geom = "point", color = "red") +
  labs(x = "Sepal Length", y = "Sepal Width",
       shape = "Shape", colour = "Species") +
  theme_classic() 

我该怎么做:

一)。更改图例,使每个分类变量的框中间没有红点? 乙)。更改“形状”图例的颜色,使“均值”为黑色,“中值”为红色?

我已经用 Google 搜索了一个多小时,但找不到答案,因此我们将不胜感激。谢谢!

【问题讨论】:

【参考方案1】:

图例指南中有 override.aes 参数,您可以使用它来明确设置键的美感。

library(ggplot2)

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, fill = Species)) + 
  geom_violin(alpha = 0.5) +
  stat_summary(aes(shape="mean",group=1),fun = "mean",
               size = 2, geom = "point", color = "black") +
  stat_summary(aes(shape = "median", group = 2), fun = "median",
               size = 2, geom = "point", color = "red") +
  labs(x = "Sepal Length", y = "Sepal Width",
       shape = "Shape", colour = "Species") +
  guides(
    shape = guide_legend(override.aes = list(colour = c("black", "red"))),
    fill = guide_legend(override.aes = list(shape = NA))
  ) +
  theme_classic() 
#> Warning: position_dodge requires non-overlapping x intervals

【讨论】:

以上是关于改变ggplot2图例中中位数和均值的颜色的主要内容,如果未能解决你的问题,请参考以下文章

ggplot2 函数中 geom_boxplot 的平均值和中值箱线图图例

ggplot2:显示 x 轴值的附加特定图例

R语言使用ggplot2包使用geom_violin函数绘制分组小提琴图(配置显示均值中位数)实战

R语言ggplot2可视化自定义多个图例(legend)标签之间的距离实战(例如,改变数据点颜色和数据点大小图例之间的距离)

ggplot2 中用于扩展图例标签的默认颜色

ggplot2中的轴变换