【发布时间】: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 thesummarise()`吗? -
您需要在 df 中提供每年的平均值,可以在 faceting 调用中拆分。