阴谋不出现

时间:2019-04-10 06:44:54

标签: r plotly

我正在尝试对此测试data.frame进行动画处理,但是plotly情节甚至没有显示出来!不过,相同的代码适用于原始plotly数据。我已仔细检查column's class,它们与plotly的示例相同。我现在很困惑为什么失败了。

这在marker模式下也有效,但在lines模式下则无效。

total <- data.frame(replicate(4,sample(0:1, 100, rep=TRUE)))
names(total) <- c("date", "frame", "P1.10", "year")
total$date <- as.numeric(as.character(t(rbind(runif(100, min=2000, max=2010)))))
f.rank <- order(total$date)
total$frame[f.rank] <- 1:nrow(total)
total$P1.10 <- as.numeric(as.character(t(rbind(runif(100, min=1, max=10)))))
total$year <- 2000



p <- total %>%
  plot_ly(
    x = ~date, 
    y = ~P1.10,
    frame = ~frame, 
    type = 'scatter',
    mode = 'lines', 
    line = list(simplyfy = F)
  ) %>% 
  layout(
    xaxis = list(
      title = "Date",
      zeroline = F
    ),
    yaxis = list(
      title = "P1.10",
      zeroline = F
    )
  ) %>% 
  animation_opts(
    frame = 100, 
    transition = 0, 
    redraw = FALSE
  ) %>%
  animation_slider(
    hide = T
  ) %>%
  animation_button(
    x = 1, xanchor = "right", y = 0, yanchor = "bottom"
  )

1 个答案:

答案 0 :(得分:2)

在示例中,您忽略了accumulate_by。您还需要一个ID字段。相同,但结合使用ggplot

set.seed(123)
library(plotly)

total <- data.frame(replicate(4,sample(0:1, 100, rep=TRUE)))
names(total) <- c("date", "frame", "P1.10", "year")
total$date <- as.numeric(as.character(t(rbind(runif(100, min=2000, max=2010)))))
f.rank <- order(total$date)
total$frame[f.rank] <- 1:nrow(total)
total$ID[f.rank] <- 1:nrow(total)
total$P1.10 <- as.numeric(as.character(t(rbind(runif(100, min=1, max=10)))))
total$year <- 2000

accumulate_by <- function(dat, var) {
  var <- lazyeval::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]])
  })
  dplyr::bind_rows(dats)
}

total <- total %>%
  accumulate_by(~ID)

p <- ggplot(total,aes(ID, P1.10, frame = frame)) +
  geom_line()

p <- ggplotly(p) %>%
  layout(
    title = "",
    yaxis = list(
      title = "P1.10",
      zeroline = F,
      tickprefix = "$"
    ),
    xaxis = list(
      title = "Date",
      zeroline = F, 
      showgrid = F
    )
  ) %>% 
  animation_opts(
    frame = 100, 
    transition = 0, 
    redraw = FALSE
  ) %>%
  animation_slider(
    currentvalue = list(
      prefix = "Day "
    )
  )