【问题标题】:How to add a mean line for grouped data plots如何为分组数据图添加平均线
【发布时间】:2021-10-08 14:24:00
【问题描述】:

我使用循环绘制每月空气质量数据的直方图,这些数据使用 facet_grid() 函数按年份分组。在我的情节中,我有一条所有年份月份的平均线,我希望它是每年每月的平均值。

我的代码是:

for (z in vec) {
  
  df.g <- pol %>% filter(poluentes==z)
  df.g$year <- as.character(df.g$year)
  df.g$month<- as.character(df.g$month)
  
  mu <- ddply(df.g, "month", summarise, grp.mean=mean(value)) # mean line 
  
  print(ggplot(df.g, aes(x=value, fill=month, color=month)) +
          geom_histogram(position="identity", alpha=0.2) +
          labs(title=z,x="µg/m3", caption = "Análise: poluente") + 
          geom_vline(data=mu, aes(xintercept=grp.mean, color=month),
                     linetype="dashed") + facet_grid(year ~.))
  
}

输出是:

如您所见,3 个直方图的平均线相同

【问题讨论】:

  • 您的 mean(value) 语句正在使用整个数据集。你能加一个group_by(year)' statement before the summarise()`吗?
  • 您需要在 df 中提供每年的平均值,可以在 faceting 调用中拆分。

标签: r ggplot2 dplyr plyr


【解决方案1】:

您的均值计算也需要包括年份:

set.seed(111)

df.g = data.frame(year = sample(18:20,1000,replace=TRUE),
month = factor(sample(3:4,1000,replace=TRUE)),
value = rnbinom(1000,mu=50,size=1))

mu = aggregate(df.g$value,list(month=df.g$month,year=df.g$year),mean)

然后通过它:

ggplot(df.g,aes(x=value,fill=month,col=month)) +
geom_histogram(bins=20,position="identity", alpha=0.2) + 
facet_grid(year ~ .) +
geom_vline(data = mu,aes(xintercept = x,col=month))

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2017-12-04
    • 2021-08-09
    • 2014-08-20
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多