2017-06-13 186 views
1

我有幾年的時間序列,需要使用plot_ly在x軸上繪製mm/dd和在y軸上繪製多年。我在這裏生成的樣本數據:如何在R中繪製多個序列/時間序列?

date<-seq(as.Date("2010-11-22"),as.Date("2016-05-26"),by ="days") 
sales = runif(2013, 2000, 6000) 
df = data.frame(date,sales) 

我繪製這些數據,並得到這個:

plot_ly(df,x= ~date) %>% add_lines(y = ~sales,color=I("red")) 

enter image description here

現在,我嘗試使用plot_ly繪製多個y軸:

plot_ly(df, x = ~date) %>% add_lines(y = ~sales, 
df$date <= "2010-12-31",color=I("red")) %>% 
      add_lines(y = ~sales, df$date <= "2013-12-31" & 
      df$date >= 2013-01-01, color = I("green")) 

但我得到了錯誤的陰謀:

enter image description here

這是什麼錯誤?

我想情節是這樣的:

enter image description here

+0

你的意思多個系列(而不是Y軸);對? – Masoud

+0

就像最後一幅圖像一樣,x軸上的mm/dd與每年不同顏色的銷售量。 –

回答

0

要在我們的df組與plotly::group_by分裂同一圖表創建不同的線路。你的情況,這是使用lubridate逐年分割來實現的:

library(plotly) 
library(lubridate) 
date <- seq(as.Date("2010-11-22"), as.Date("2016-05-26"), by = "days") 
# Add some variations to distinguish lines 
sales <- runif(2013, 10, 20) + year(date) * 5 + yday(date)/5 
df <- data.frame(date, sales) 


df %>% 
    mutate(year = year(date)) %>% 
    group_by(year) %>% 
    plot_ly(x = ~ yday(date)) %>% 
    add_lines(y = ~ sales, 
      color = ~ factor(year) 
      ) 

enter image description here

+0

您可以在x軸上繪製mm/dd而不是日數? –