echarts4r e_line color by categorical variable

k4ymrczo  于 2023-04-03  发布在  Echarts
关注(0)|答案(1)|浏览(133)

我想做这样的图(这里来自Our World In数据),但其中的线颜色因分类变量而异。例如,y值高于0.3,则为预警=橙子,高于0.6,则为预警=红色。

x <- seq(from = 1,
           to = 100,
           b = 1)
  y <- sin(x) 
  
  df <- data.frame(x = x, y = y)
  df<- df %>% mutate(alert = case_when(
    y > 0.3  ~  "pre_alert",
    y > 0.6 ~  "alert",
    TRUE ~ "normal"
  ))
  df <- data.frame(df)
  
  df %>%
    e_charts(x = x) %>%
    e_line(serie = `y`) %>%   
    e_tooltip(trigger = "axis")%>%
    e_color(my_colors)%>%
    e_legend(orient = 'vertical', 
             right = '5', top = '15%')
a0x5cqrl

a0x5cqrl1#

一个选择是使用e_visual_map。不幸的是,文档非常少,但基于[这个例子],我们可以使用pieces来定义y列的范围,即不需要创建分类变量:

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

相关问题