简体   繁体   English

plotly R 中的多行不使用 add_trace

[英]Multiple lines in plotly R not using add_trace

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.我想绘制超过在同一时间序列图中的一列(A,B,C ...),没有使用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.原因是我正在构建一个 Shiny 应用程序,用户可以在其中动态选择,使用 selectize 输入,哪些变量要绘制,因此要动态执行,必须不要采用 add_trace 方式。

Is there another way to achieve that?有没有另一种方法来实现这一目标?

Thanks.谢谢。

Edit:编辑:

Output of the dput(data_example) 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))

You should reshape your data.frame to long format.您应该将data.frame重塑为长格式。

I prefer library(data.table) for this - see the melt call. library(data.table)我更喜欢library(data.table) - 请参阅melt调用。 After that you may use split or color to generate the traces:之后,您可以使用splitcolor来生成跟踪:

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)

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM