我想在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条线,则每个面显示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相关问答推荐

使用gggplot 2在R中正确表示翻转堆叠条形图中的数据

使用facet_wrap()时如何将面板标题转换为脚注?

我可以截断10字节的扩展数并转换为8字节的double吗?

在水平条形图中zoom x_轴

列出用m n个值替换来绘制n个数字的所有方法(i.o.w.:R中大小为n的集合的所有划分为m个不同子集)

R中具有gggplot 2的Likert图,具有不同的排名水平和显示百分比

如何在R中添加截止点到ROC曲线图?

如何从当前行上方找到符合特定条件的最接近值?

S用事件解决物质平衡问题

无法定义沿边轨迹的 colored颜色 渐变(与值无关)

如何通过匹配R中所有可能的组合来从宽到长旋转多个列?

根据约束随机填充向量的元素

我们如何在R中透视数据并在之后添加计算

减go R中列表的所有唯一元素对

警告消息";没有非缺失的参数到min;,正在返回数据中的inf";.表分组集

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

如何在AER::ivreg中指定仪器?

为什么将负值向量提升到分数次方会得到NaN

ggplot斜体轴刻度标签中的单个字符-以前的帖子建议不工作

如果满足条件,则替换列的前一个值和后续值