当 variables/columns 的数量总是不同时,用 plotly 绘制折线图

plot line chart with plotly when having always different number of variables/columns

我想使用以下数据table(只是一个反例)创建一个线图:

dt <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                 Germany = rnorm(365, 2, 1), Austria = rnorm(365, 3, 4), 
                 Czechia = rnorm(365, 2, 3), check.names = FALSE)

情节的代码如下所示:

p <- plot_ly(dt, x = ~dt$date, y = ~dt$Germany, mode = 'lines', type = 'scatter', 
             line = list(color = "#007d3c"), 
             connectgaps = TRUE, name = dt[, 2],
             hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                                   "%{y} \u20ac/MWh <br>")) %>%
     add_trace(y = ~dt$Austria, name = dt[, 3],
               line = list(color = "#007d3c", width = 3, dash = 'dot')) %>%
     add_trace(y = ~dt$Czechia, 
               line = list(color = "#b4b4b4", width = 3, dash = 'dash'), 
               name = dt[, 4]) %>%
     layout(title = "<b>Coal", xaxis = list(title = "Date"), 
            yaxis = list(title = "EUR/MWh"), showlegend = FALSE)

基本上一切都按预期工作,但我的数据 table 永远不必看起来像这样。第一列 (date) 始终保持不变,但每个附加列有时可以有不同的名称。另外,可能是数据table比dt中的上述数据table多了或者少了列。我仍然想创建一个线图来匹配这种情况。例如,table 可以(在选择其他输入后)具有以下列:

日期 |德国 |荷兰

或:日期 |奥地利 |斯洛文尼亚 |丹麦

此外,如果使用相应的列名而不是 trace 0trace 1 等,那就太好了。

这将如何运作?

对于这种情况,最佳做法是通过 melt.data.table:

data.table 从宽格式转换为长格式
library(plotly)
library(data.table)


DT <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                 Germany = rnorm(365, 2, 1), Austria = rnorm(365, 3, 4), 
                 Czechia = rnorm(365, 2, 3), check.names = FALSE)


DT <- melt.data.table(DT, id.vars = "date")

p <- plot_ly(DT, x = ~ date, y = ~ value, color = ~ variable, mode = 'lines', type = 'scatter',
             connectgaps = TRUE, name = DT[, 2],
             hovertemplate = paste("%{xaxis.title.text}:  %{x}<br>",
                                   "%{y} \u20ac/MWh <br>")) %>%
  layout(title = "<b>Coal", xaxis = list(title = "Date"), 
         yaxis = list(title = "EUR/MWh"), showlegend = FALSE)

p