如何在 R 中使用 highcharter 创建动态折线图

How to create motion line chart wth highcharter in R

我正在尝试创建动态折线图。该功能如下所示

library(highcharter)
library(magrittr)

highchart() %>% 
  hc_chart(type = "line") %>% 
  hc_yAxis(max = 12, min = 0) %>%
  hc_xAxis(categories = c(1, 1.7, 1, 0)) %>% 
  hc_add_series(data = list(
              list(sequence = c(1,1,1,1)),
              list(sequence = c(NA,2,2,2)),
              list(sequence = c(NA,NA,5,5)),
              list(sequence = c(NA,NA,NA,10))
            )) %>% 
  hc_motion(enabled = TRUE, labels = 1:4, series = 0)

但我希望最终结果如下所示,使用 hc_motion 选项

hchart(data.frame(xx=c(1, 1.7, 1, 0), yy=c(1, 2, 5, 10)), 
       type = "line", hcaes(x = xx, y = yy))

即问题出在第一种情况下,动态图表将 xAxis 视为类别,而我希望它像一个带有直线的散点图。

经过一番搜索,我找到了答案

library(highcharter)
library(magrittr)

创建数据

df <- data.frame(xx=c(1, 1.7, 1, 0), yy=c(1, 2, 5, 10))
df$key <- 0
df <- lapply(1:dim(df)[1], function(x){ df$key <- df$key+x; df}) %>% 
do.call(rbind, .)
df %<>% group_by(key) %>% mutate(key2=1, key2=cumsum(key2)) %>% ungroup %>% 
  mutate(yy=ifelse(key<key2, NA, yy))

一些操纵

highcharter 加上 hc_motion

df1 <- df %>% filter(key==1) %>% select(-key)
df2 <- df %>% group_by(key2) %>% do(sequence = list_parse(select(., y = yy))) %>% ungroup
df <- left_join(df1, df2, by="key2")
df %<>% select(xx, yy, sequence)

图表

highchart() %>% hc_yAxis(min = 0, max = 10) %>%
  hc_add_series(data = df, type = "line", hcaes(x = xx, y = yy)) %>%
  hc_motion(enabled = TRUE, series = 0, startIndex = 0, labels = 1:4)