如何为分组数据图添加平均线
How to add a mean line for grouped data plots
我使用循环绘制每月空气质量数据的直方图,这些数据使用 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 个直方图的平均线相同
您的均值计算还需要包括年份:
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))
我使用循环绘制每月空气质量数据的直方图,这些数据使用 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 个直方图的平均线相同
您的均值计算还需要包括年份:
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))