ggplot 中每个面都有不同的垂直线

out*_*een 4 r ggplot2

我想在 ggplot 图的每个方面显示一个垂直条,其中包含该方面数据的平均值。我可以针对单个方面执行此操作:

# For Petal Length Only :
Mean <- colMeans(iris["Petal.Length"])
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>% 
  filter(Characteristic=="Petal.Length") %>%
  ggplot(aes(x=Value,fill=Species))+geom_density()+facet_wrap(~Characteristic)+
geom_vline(xintercept = Mean)
Run Code Online (Sandbox Code Playgroud)

但是当使用小平面时,会显示 4 条垂直线,而不是每个小平面显示一条:

# For all characteristics :
Mean <- colMeans(iris[-5])
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>%
  

ggplot(aes(x=Value,fill=Species))+geom_density()+facet_wrap(~Characteristic)+geom_vline(xintercept = Mean)
# Display vertical lines for all means where I would like only one vertical bar
# by group displayed (one for petal length, one for sepal width, etc)
 
# for example for Petal Length, only the vertical line with intercept colMeans(iris["Petal.Length"]) should be displayed.
 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 6

问题在于“平均”变量。其格式与原始数据集不一致。以相同的方式构建它,刻面将按预期工作。

library(dplyr)
library(tidyr)
library(ggplot2)
# For all characteristics :
Mean <- colMeans(iris[-5]) %>% as_tibble(rownames = "Characteristic")
iris %>% pivot_longer(cols = !Species,names_to = "Characteristic",values_to = "Value") %>%
  ggplot(aes(x=Value,fill=Species))+
  geom_density()+
  geom_vline(aes(xintercept = value),data=Mean) +
  facet_wrap(~Characteristic) 
Run Code Online (Sandbox Code Playgroud)