每个面板都有不同的垂直线,在ggplot中如何实现?

4

我希望在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)

但是使用facets时,每个facet显示的垂直线条不止一个,而是四个:

# 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.
 

enter image description here

1个回答

6
问题出在'Mean'变量上,它的格式与主数据集不一致。按照相同的方式结构化它,分面图将按预期工作。
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) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接