向平面添加平均值

时间:2015-02-17 15:28:02

标签: r ggplot2 facet-wrap

我有这个情节,它计算一个特定冬季鸟类物种的丰度指数: Facet by year 此图形来自此代码(不包括主题和比例):

ggplot (a, aes (pentada,ika,colour=inv,group=inv,na.rm=T)) + geom_line()+
facet_wrap(~inv, ncol=3)+labs(title="SYLATR\n",x="",y="IKA")

,数据框有6个变量:

pentada / censos / yr / total / inv / ika

事情是,我想在每个越冬季节添加一条线,显示所有年份的总和的平均值,我不知道如何。我应该在每个越冬季节之后将平均值作为新列添加吗?在这种情况下,我该怎么做?。

谢谢。

1 个答案:

答案 0 :(得分:3)

我不确定你是否想要全球均值,即平均冬天和天数。如果是这样,那么上面的影子解决方案可能是最好的;这样的事情也会这样做:

#toy data
df <- data.frame(t = rep(1:100,9), pop = rnorm(900)+20, 
    year = rep(letters[1:9], 9, each = 100))

#make graph
ggplot(data = df, aes(x = t, y = pop, colour = year, na.rm=T)) + 
    geom_line() + facet_wrap(~year, ncol = 3) + 
    geom_line(aes(x=t, y = mean(pop)))

如果你想要仅限于平均值,那么白天仍然存在动态,我认为你应该在调用ggplot之前先将它添加到数据框中。

#aggregate the mean population over years but not days
yearagg.df <- aggregate(data = df, pop ~ t, mean)

#make plot
ggplot(data = df, aes(x = t, y = pop, colour = year, na.rm=T)) + 
    geom_line() + 
    facet_wrap(~year, ncol = 3) + 
    geom_line(data = yearagg.df, aes(y = pop, x=t), color = 'black')

第二个代码段会生成此图表:

Graph of 2nd code snippet with mean-over-years-only

更新: 如果将平均数据放回数据框中,您可能会更容易地进行绘图,以便您可以绘制来自同一数据框的所有图层而不是将来自多个帧的数据混合/匹配到一个图中。

df.m <- merge(df, yearagg.df, by = 't', suffixes = c('.raw', '.mean'))
ggplot(data = df.m, aes(x = t, colour = year, na.rm=T)) + 
    geom_line(aes(y = pop.raw)) + 
    facet_wrap(~year, ncol = 3) + 
    geom_line(aes(y = pop.mean), color = 'gray')