在ggplot2中叠加线条图

时间:2014-11-21 20:47:10

标签: r ggplot2 overlay linegraph

我使用ggplot2创建了一个多线图,其中每一行代表一个相对于月绘制的年份(点击下面的链接)。体积在y轴上表示。

http://imgur.com/3Rwdjyi

以下是我用来绘制上图的代码:

ggplot(data=df26, aes(x=Month, y=C1, group=Year, colour=factor(Year))) + 
    geom_line(size=.75) + geom_point() +    
    scale_x_discrete(limits=c("Jan","Feb","Mar","Apr","May","Jun","Jul",
        "Aug","Sep","Oct","Nov","Dec")) + 
    scale_y_continuous(labels=comma) + 
    scale_colour_manual(values=cPalette, name="Year") +    
    ylab("Volume")   

问题:我如何在图中添加另一条线来表示每个月内的平均体积,并能够修改该线的粗线和颜色?到目前为止,我生成正确代码的所有尝试都没有成功(很可能是因为我使用R的相对新手状态)。非常感谢任何帮助!

修改:下方提供了数据框df26(根据评论者的要求):

Year  Month   C1
2010  Jan NA
2010  Feb NA
2010  Mar NA
2010  Apr NA
2010  May NA
2010  Jun NA
2010  Jul NA
2010  Aug 183.6516764
2010  Sep 120.6303348
2010  Oct 85.31007613
2010  Nov 13.7347988
2010  Dec 20.93950545
2011  Jan 13.35780833
2011  Feb 14.16910945
2011  Mar 9.786319721
2011  Apr 41.24848885
2011  May 122.3014387
2011  Jun 422.4012809
2011  Jul 539.8569592
2011  Aug 527.6301222
2011  Sep 385.8199781
2011  Oct 201.7846973
2011  Nov 27.91934061
2011  Dec 7.919004379
2012  Jan 10.22724424
2012  Feb 10.64391791
2012  Mar 88.06585438
2012  Apr 124.0320675
2012  May 325.1399457
2012  Jun 465.938168
2012  Jul 567.2273488
2012  Aug 459.769634
2012  Sep 333.8636373
2012  Oct 102.0607986
2012  Nov 23.18822051
2012  Dec 15.64841121
2013  Jan 7.458238256
2013  Feb 4.34972039
2013  Mar 26.2019396
2013  Apr 38.82781323
2013  May 257.0920645
2013  Jun 357.594195
2013  Jul 383.2780483
2013  Aug 456.469314
2013  Sep 319.3616298
2013  Oct NA
2013  Nov NA
2013  Dec 17.01748185

1 个答案:

答案 0 :(得分:3)

您需要计算均值。然后你可以绘制它们。 使用dplyr

library(dplyr)
df26means <- df26 %>%
    group_by(Month) %>%
    summarize(C1 = mean(C1, na.rm = T))

然后将其添加到你的情节中:

ggplot(data=df26, aes(x=Month, y=C1, group=Year, colour=factor(Year))) + 
    geom_line(size=.75) + geom_point() + 
    scale_x_discrete(limits=c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                              "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")) + 
    scale_y_continuous(labels=comma) + 
    scale_colour_manual(values=cPalette, name="Year") + 
    ylab("Volume") +
    geom_line(data = df26means, aes(group = 1), size = 1.25, color = "black")

我建议使用annotate在图表上添加一段漂亮的文字,将该行标识为平均线。要在图例中获取它,您可能需要设置df26means$Year = "Mean",将df26$Year转换为字符,rbind将两个数据帧放在一起,然后将Year转换为一个因素。绘图代码会更简单,但数据争论有点复杂。