2015-06-12 51 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'似乎很好。有什麼問題? –