1
votes

I have a dataframe containing time series data, formed by 3 columns. time, variable and category. I want to plot the time in the x axis and the variable in the y axis, and I want to make groups based on category. Additionally, I would like to modify the default markers created by plotly, so they display a rounded value of the variable.

Consider the following example:

var = rnorm(150)
var[51:100] = var[51:100] +5
var[101:150] = var[101:150] +10
time = seq(as.Date('2018-01-01'), as.Date('2018-01-01')+49, by = 'days')

df = tibble(var = var,
        time = rep(time, 3),
        category = c(rep('a', 50), rep('b', 50), rep('c', 50)))
head(df)
 var       time     category
<dbl>     <date>    <chr>   
1  0.330  2018-01-01 a       
2 -0.786  2018-01-02 a       
3 -0.838  2018-01-03 a       
4 -0.0719 2018-01-04 a       
5  0.0320 2018-01-05 a       
6 -1.16   2018-01-06 a  

library(plotly)
df %>% group_by(category) %>% 
   plot_ly(x = ~ time, y = ~ var, color = ~ category, mode = 'lines+markers')

This generates the kind of plot that I want: see here, but when I try to modify the the markers:

df %>% group_by(category) %>% 
  plot_ly(x = ~ time, y = ~ var, color = ~ category, mode = 'lines+markers') %>%
  add_markers(text = ~ paste("<b>Variable:</b> ", round(var, 2), 
                         "<br />",
                         "<b>Time:</b> ", time), hoverinfo = "text")

It transforms the plot drawing just the dots but not the lines.see here. If I try to force adding the lines with the command add_lines() then I have a double legend, with values for the dots and the lines separatedly.

df %>% group_by(category) %>% 
  plot_ly(x = ~ time, y = ~ var, color = ~ category, mode = 'lines+markers') %>%
  add_markers(text = ~ paste("<b>Variable:</b> ", round(var, 2), 
                         "<br />",
                         "<b>Time:</b> ", time), hoverinfo = "text") %>% 
  add_lines()

Is there a way to plot a time series with plotly that includes lines, and customized markers? Im sorry if this is a silly question, I am quite new to plotly.

1
With regard to your last example, to remove one of two legends, just add showlegend = F to either add_markers or add_lines.Ben

1 Answers

0
votes

If you want one trace with both markers and lines then stick with the plot_ly function instead of adding traces. Try this:

library(plotly)

df %>% 
  group_by(category) %>% 
  plot_ly(x = ~ time, y = ~ var, color = ~ category, mode = 'lines+markers', type = "scatter",
          text = ~ paste("<b>Variable:</b> ", round(var, 2), 
                         "<br />",
                         "<b>Time:</b> ", time), hoverinfo = "text")