Ankit Gupta
Ankit Gupta

Reputation: 49

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

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

enter image description here

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:

enter image description here

What's the mistake in that?

I want the plot like this:

enter image description here

Upvotes: 4

Views: 5833

Answers (1)

GGamba
GGamba

Reputation: 13680

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

enter image description here

Upvotes: 3

Related Questions