根据组调整ggplot中geom_vline的颜色

Adjust color of geom_vline in ggplot based on group

所以我正在为虹膜数据集的两个物种创建 Sepal.Length 的密度图。该图如下所示:

如您所见,我在图表中添加了两种集中趋势度量(中位数和均值)。但是,现在它们的颜色取决于度量(即中位数 = 黑色,均值 = 灰色)。

我想更改颜色,使 Setosa/Versicolor 的均值和中位数具有相同的颜色。此外,我想为 setosa/versicolor 的 mean/median 添加一个指示颜色和线型的图例。所以最后我会有一个由四个部分组成的图例:Median Setosa、Mean Setosa、Median Versicolor、Mean Versiocolor。

有人知道怎么做吗?请参阅下面的复制代码:

library(ggplot2)
library(tidyverse)

iris <- iris %>%
  filter(Species == c("setosa", "versicolor"))

temp <- iris %>% 
  group_by(Species) %>%
  dplyr::summarize(Mean = mean(Sepal.Length, na.rm=TRUE))

temp_2 <- iris %>% 
  group_by(Species) %>%
  dplyr::summarize(Median = median(Sepal.Length, na.rm=TRUE))

ggplot(iris, aes(x = Sepal.Length, fill = factor(Species))) +
  geom_density(alpha = 0.5) +
  theme_minimal() +
  geom_vline(data=temp, aes(xintercept=Mean, color="Mean"),
             linetype="dotted", 
             lwd=1) +
  geom_vline(data=temp_2, aes(xintercept=Median, color="Median"),
             linetype="dashed", 
             lwd=1) +
  scale_color_manual(name = "Statistics", values = c(Median = "black", Mean = "grey50")) + 
  labs(title = "Distribution of Sepal.Length",
       x = "Sepal.Length",
       y = "Density",
       fill = "Species") 

这个比较复杂。您需要将线条的线型和颜色映射到 Species 和表示中位数或均值的字符串的交互,而不是适当地指定手动比例:

ggplot(iris, aes(x = Sepal.Length, fill = factor(Species))) +
  geom_density(alpha = 0.5) +
  theme_minimal() +
  geom_vline(data=temp, aes(xintercept=Mean, 
                            color = interaction(Species, 'Mean'),
                            linetype = interaction(Species, 'Mean')),
             lwd = 1, key_glyph = draw_key_path) +
  geom_vline(data=temp_2, aes(xintercept=Median, 
                              color = interaction(Species, 'Median'),
                              linetype = interaction(Species, 'Median')),
             lwd=1,  key_glyph = draw_key_path) +
  scale_linetype_manual(values = c(setosa.Mean = 'dotted', 
                                   setosa.Median = 'dashed',
                                   versicolor.Mean = 'dotted',
                                   versicolor.Median = 'dashed'),
                        name = 'Averages') +
  scale_color_manual(values = c(setosa.Mean = "#F8766D", 
                                   setosa.Median = "#F8766D",
                                   versicolor.Mean = "#00BFC4",
                                   versicolor.Median = "#00BFC4"),
                     name = 'Averages') +
  labs(title = "Distribution of Sepal.Length",
       x = "Sepal.Length",
       y = "Density",
       fill = "Species") +
  theme(legend.key.width = unit(15, 'mm'))