5

I am trying to create a motion line chart. The functionality would look something like the below

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)

motion line chart

But i would like the end result to look like the below, using the hc_motion option

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

spline

i.e the problem is in the first case the motion chart treats the xAxis as categories, whereas i would like it to be like a scatter plot with straight lines.

dimitris_ps
  • 5,849
  • 3
  • 29
  • 55

1 Answers1

1

After some searching I've got the answer

library(highcharter)
library(magrittr)

Create data

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))

Some manipulation

To bring into a form for highcharter with 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)

graph

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)

solution

dimitris_ps
  • 5,849
  • 3
  • 29
  • 55
  • 1
    Nice question and nice answer! – jbkunst Apr 06 '17 at 13:30
  • @jbkunst thanks man. Exceptional work you've done with the package. This question is just part of another visualization i want to create, i will share it with you if i manage to complete it. Thanks for the great work. – dimitris_ps Apr 06 '17 at 13:33
  • @dimitris-ps Please I would love to see it! Recently I'm using a lot the motion plugin so will be nice to see other examples :D. Thanks for use the package ;) – jbkunst Apr 06 '17 at 15:00