首页 > 解决方案 > 改变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") +
  theme_classic() 

虹膜图

我如何能:

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

我已经用 Google 搜索了一个多小时,但找不到答案,因此非常感谢您的帮助。谢谢!

标签: rggplot2meanmedianviolin-plot

解决方案


图例指南有一个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


推荐阅读