如何在R中使用plotly绘制时间序列中的多个序列/线?

如何在R中使用plotly绘制时间序列中的多个序列/线?

问题描述:

我有几年的时间序列,需要使用plot_ly在x轴上绘制mm/dd,在y轴上绘制多年.我在这里生成了示例数据:

I have a time series of several years that I need to plot mm/dd on the x-axis and multiple years on the y-axis using plot_ly. I have generated a sample data here:

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

我绘制了这些数据并得到了:

I plotted this data and get this:

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

现在,我尝试使用 plot_ly 绘制多个y轴:

Now, I tried to plot multiple y-axis using plot_ly:

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"))

但是我弄错了情节:

这是什么错误?

我想要这样的情节:

要在同一图上创建不同的线,我们必须使用 plotly :: group_by 将 df 分组分组.代码>.在您的情况下,可以使用 lubridate 按年份进行拆分:

To create different lines on the same graph we have to split the df in group with plotly::group_by. In your case this is achieved using lubridate to split by year:

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)
            )