Home > Enterprise >  Multiple lines in plotly R not using add_trace
Multiple lines in plotly R not using add_trace

Time:10-15

I have this kind of data:

> data_example
          date   A   B   C   D   E   F
1   2020-09-22 1.3 0.0 1.3 0.3 0.9 0.0
2   2020-09-23 0.7 0.0 0.7 0.0 0.7 0.0
3   2020-09-24 0.4 0.0 0.4 0.0 0.4 0.0
4   2020-09-25 0.2 0.2 0.5 0.0 0.2 0.0
5   2020-09-26 1.0 0.0 1.0 0.0 1.0 0.0
6   2020-09-27 0.2 0.2 0.5 0.1 0.1 0.0
7   2020-09-28 0.6 0.1 0.7 0.0 0.6 0.0
8   2020-09-29 0.4 0.1 0.5 0.1 0.2 0.0
9   2020-09-30 0.4 0.1 0.6 0.0 0.4 0.0
10  2020-10-01 1.0 0.1 1.1 0.8 0.1 0.0
11  2020-10-02 0.6 0.1 0.8 0.2 0.4 0.0

I would like to plot more than one of the columns (A, B, C...) in the same time series plot BUT without using the add_trace. The reason is I am building a Shiny app where dynamically the user can choose, using the selectize input, which variables want to plot, so to do it dynamically it's a must to not to be in an add_trace way.

Is there another way to achieve that?

Thanks.

Edit:

Output of the dput(data_example)

data_example <- structure(list(date = c("2020-09-22", "2020-09-23", "2020-09-24", 
"2020-09-25", "2020-09-26", "2020-09-27", "2020-09-28", "2020-09-29", 
"2020-09-30", "2020-10-01", "2020-10-02"), A = c(1.3, 0.7, 0.4, 
0.2, 1, 0.2, 0.6, 0.4, 0.4, 1, 0.6), B = c(0, 0, 0, 0.2, 0, 0.2, 
0.1, 0.1, 0.1, 0.1, 0.1), C = c(1.3, 0.7, 0.4, 0.5, 1, 0.5, 0.7, 
0.5, 0.6, 1.1, 0.8), D = c(0.3, 0, 0, 0, 0, 0.1, 0, 0.1, 0, 0.8, 
0.2), E = c(0.9, 0.7, 0.4, 0.2, 1, 0.1, 0.6, 0.2, 0.4, 0.1, 0.4
), F = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c(NA, 
-11L))

CodePudding user response:

You should reshape your data.frame to long format.

I prefer library(data.table) for this - see the melt call. After that you may use split or color to generate the traces:

library(data.table)
library(plotly)

DF <- data.frame(
  date = c("2020-09-22","2020-09-23","2020-09-24",
           "2020-09-25","2020-09-26","2020-09-27","2020-09-28",
           "2020-09-29","2020-09-30","2020-10-01","2020-10-02"),
  A = c(1.3, 0.7, 0.4, 0.2, 1, 0.2, 0.6, 0.4, 0.4, 1, 0.6),
  B = c(0, 0, 0, 0.2, 0, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1),
  C = c(1.3, 0.7, 0.4, 0.5, 1, 0.5, 0.7, 0.5, 0.6, 1.1, 0.8),
  D = c(0.3, 0, 0, 0, 0, 0.1, 0, 0.1, 0, 0.8, 0.2),
  E = c(0.9, 0.7, 0.4, 0.2, 1, 0.1, 0.6, 0.2, 0.4, 0.1, 0.4),
  F = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
)

setDT(DF)

longDF <- melt(DF, id.vars = "date")

plot_ly(longDF, type = "scatter", mode = "lines markers", x = ~date, y = ~value, split = ~variable)

result

  • Related