R动画动画:折线图不绘制线

R animated plotly: line graph not plotting line

我正在尝试使用我自己的数据在 R 中创建动画绘图线图。当我使用标记作为 'mode' 时动画有效,但是,当将模式更改为 'lines' 或 'plines' 时,图表上没有任何显示。

有什么建议吗?

数据:

CH4

X FIRST SECOND
1 1 23.9 71.9
2 2  2.9 23.7
3 3 85.7  6.0
4 4  1.2 94.0
5 5  1.1 66.8
6 6  1.5 99.9

代码:

plot_ly(CH4, x=~X, y=~FIRST, name="FIRST",
        hoverinfo = 'text',
        text = ~paste('Test Round: ', CH4$X, '<br>',
                      'Concentration: ', CH4$SECOND),
        type = "scatter", mode = "plines", frame=~frame) %>%
  add_trace(x=~X, y = ~SECOND, name="SECOND", mode = 'plines') %>%

  layout(yaxis = list(title = "CH4 Concentrations"), xaxis = list(title = 
 "Test Round"))

您可以找到解决方案here
从您的数据开始,您需要生成一个 accumulated 数据框,例如使用下面定义的 accumulate_by 函数。

dts <- read.table(text="
X FIRST SECOND
1 1 23.9 71.9
2 2  2.9 23.7
3 3 85.7  6.0
4 4  1.2 94.0
5 5  1.1 66.8
6 6  1.5 99.9
", header=T)

library(plotly)
library(lazyeval)
library(dplyr)
accumulate_by <- function(dat, var) {
  var <- f_eval(var, dat)
  lvls <- plotly:::getLevels(var)
  dats <- lapply(seq_along(lvls), function(x) {
    cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
  })
  bind_rows(dats)
}

CH4 <- dts %>% accumulate_by(~X)
head(CH4, 10)
#    X FIRST SECOND frame
# 1  1  23.9   71.9     1
# 2  1  23.9   71.9     2
# 3  2   2.9   23.7     2
# 4  1  23.9   71.9     3
# 5  2   2.9   23.7     3
# 6  3  85.7    6.0     3
# 7  1  23.9   71.9     4
# 8  2   2.9   23.7     4
# 9  3  85.7    6.0     4
# 10 4   1.2   94.0     4

现在您的代码可以正常工作了:

plot_ly(CH4, x=~X, y=~FIRST, frame=~frame, 
        name='FIRST',  hoverinfo = 'text',
        text = ~paste('Test Round: ', CH4$X, '<br>',
                      'Concentration: ', CH4$SECOND),
        type = 'scatter', mode = 'plines') %>%
  add_trace(x=~X, y = ~SECOND, name='SECOND', mode = 'plines') %>%
  layout(yaxis = list(title = 'CH4 Concentrations'), 
         xaxis = list(title = 'Test Round'))