How to plot multiple series/lines in a time series using plotly in R?

拥有回忆 提交于 2021-01-23 01:59:12

问题


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

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

but I got wrong plot:

What's the mistake in that?

I want the plot like this:


回答1:


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



来源:https://stackoverflow.com/questions/44522306/how-to-plot-multiple-series-lines-in-a-time-series-using-plotly-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!