gpt4 book ai didi

r - ggplot中每个方面的不同垂直线

转载 作者:行者123 更新时间:2023-12-02 18:17:29 32 4
gpt4 key购买 nike

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

enter image description here

最佳答案

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

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)

关于r - ggplot中每个方面的不同垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71393831/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com