我想在 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 條垂直線,而不是每個構面的 1 條:
# 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.

uj5u.com熱心網友回復:
問題在于那個“平均”變數。其格式與原始資料集不一致。以相同的方式構建它,刻面將按預期作業。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440266.html
上一篇:如何使用“from-to-dataframe”制作網路圖?
下一篇:在拼布中手動定位圖例
