2015-06-12 127 views
0

我的数据的多元时间序列数据如下:绘图中的R

> head(Full.df) 
     Date  Month  Week  Year Count.S Count.G Count.W Count.F 
1 2006-01-02 2006-01-01 2006-01-02 2006-01-01  0  7  9  6 
2 2006-01-03 2006-01-01 2006-01-02 2006-01-01  0  13  12  4 
3 2006-01-04 2006-01-01 2006-01-02 2006-01-01  0  13  15  4 
4 2006-01-05 2006-01-01 2006-01-02 2006-01-01  0  20  6  3 
5 2006-01-06 2006-01-01 2006-01-02 2006-01-01  0  19  19  4 
6 2006-01-07 2006-01-01 2006-01-02 2006-01-01  0  4  16  5 

为我所用的下一行代码的单一变量:

ggplot(data = Full.df, aes(Month, Count.S)) + stat_summary(fun.y = sum, geom ="line") + scale_x_date(
labels = date_format("%m-%y"), 
breaks = "3 months") 

我想绘制Count.SCount.G,Count.W,Count.F作为四条线在同一平面上,但我不知道如何绘制ggplot(或任何其他包)的所有四个变量。谢谢。

编辑:虽然提供给不同问题的链接是非常有用的,但那里的答案解释了如何在一个图像中绘制不同的图。但是,我想知道如何在单个XY轴上绘制与各种变量相对应的线条。

+0

我认为'library(reshape2)'和'melt'会做到这一点......你可以通过变量进行分组和颜色......'id.vars'将会是你的日期列... – drmariod

回答

1

两个这样做的方法:

如果作为创建的样本数据如下:使用reshape2包

Full.df <- data.frame(Date = as.Date("2006-01-01") + as.difftime(0:364, units = "days")) 
Full.df$Month <- as.Date(format(Full.df$Date, "%Y-%m-01")) 
Full.df[paste0("Count.", c("S", "G", "W", "F"))] <- 
    matrix(sample(100, 365 * 4, replace = TRUE), ncol = 4) 

最佳的方式:

molten <- melt(Full.df, id.vars = c("Date", "Month"), 
    variable.name = "Category", value.name = "Count") 
ggplot(data = molten, aes(x = Month, y = Count, colour = Category)) + 
    stat_summary(fun.y = sum, geom ="line") + 
    scale_x_date(labels = date_format("%m-%y"), breaks = "3 months") 

替代使用多个geoms但没有传说:

ggplot(Full.df, aes(x = Month)) + 
    stat_summary(aes(y = Count.S), colour = "blue", fun.y = sum, geom = "line") + 
    stat_summary(aes(y = Count.G), colour = "red", fun.y = sum, geom = "line") + 
    stat_summary(aes(y = Count.W), colour = "green", fun.y = sum, geom = "line") + 
    stat_summary(aes(y = Count.F), colour = "orange", fun.y = sum, geom = "line") + 
    scale_x_date(labels = date_format("%m-%y"), breaks = "3 months") 
+0

谢谢,非常有帮助! – Zlo

+0

当数据帧中有NA时,是否有可能使用熔融法? – Zlo

+0

@Zlo对'data.frame'中的'NA'似乎很好。有什么问题? –