2017-06-13 155 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而不是日数? –