echarts4r e_line color by categorical variable

192 views Asked by At

I want to make this kind of graph (here from Our World In data ) but where the line colour varies by categorical variable. Since the calculated threshold is seasonal, I would need to use a categorical variable (see the Alert variable). Based on Stephan's answer, I made this script, and it's true that the document about the e_visual_map is quite scare.

Our world in data

    x <- seq(
  from = 1,
  to = 100,
  b = 1
)
y <- sin(x)

df <- data.frame(x = x, y = y)


df1<- df %>% 
  mutate(rM = rollmean(
    y,
    3,
    na.pad = TRUE,
    align = "center"
  )) %>% mutate(
    Threshold = round(rM, 2)
  )  %>% mutate (Alert = y > Threshold) %>%mutate(
    Alert = case_when(
      Alert == "FALSE" ~ 0,
      TRUE ~ 1
    )
  )

df1 |>
  e_charts(x) |>
  e_line(y) |>
  e_visual_map(
    Alert,
    type = "continuous",
    inRange = list(color = c("#f6efa6","#bf444c")),
    bottom = 300 # padding to avoid visual maps overlap
  )
1

There are 1 answers

1
stefan On

One option would be to use e_visual_map. Unfortunately the docs are quite scare but based on [this example] we could use pieces to define the ranges for your y column, i.e. there is no need to create a categorical variable:

library(echarts4r)
library(magrittr)

x <- seq(
  from = 1,
  to = 100,
  b = 1
)
y <- sin(x)

df <- data.frame(x = x, y = y)

df %>%
  e_charts(x) %>%
  e_line(y) %>%
  e_tooltip(trigger = "axis") %>%
  e_legend(
    show = FALSE
  ) %>%
  e_visual_map(
    type = "piecewise",
    pieces = list(
      list(lte = .3, color = "green", label = "normal"),
      list(gt = .3, lte = .6, color = "orange", label = "pre-alert"),
      list(gt = .6, color = "red", label = "alert")
    ),
    right = "5", 
    top = "15%"
  )

enter image description here