簡體   English   中英

ggplot中每個方面的不同垂直線

[英]Different vertical line for each facet in ggplot

我想在 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)

但是當用面做時,每個面顯示 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.
 

在此處輸入圖像描述

問題出在那個“平均”變量上。 其格式與原始數據集不一致。 以相同的方式構造它,分面將按預期工作。

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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM