Echarts4r 的条形图起始值不是 0

Dav*_*vid 3 r echarts echarts4r

我想用来echarts4r绘制一个条形图,其中截止值以上的值涂为绿色,低于红色,并且条形从该值开始。如果截止值为 0,我们可以使用此处提供的答案,对于其他值(例如下面示例中的 1),这效果不佳,因为条形始终从零开始。有没有办法让栏从其他值开始?

请参阅下面的 MWE:

library(echarts4r)
set.seed(1)
df <- data.frame(
  x = 1:10,
  y = 1 + cumsum(rnorm(10, 0, 0.1))
)
df %>% 
  e_charts(x) %>% 
  e_bar(y) %>% 
  e_visual_map(
    type = "piecewise",
    pieces = list(
      list(
        gt = 1,
        color = "green"
      ),
      list(
        lte = 1,
        color = "red"
      )
    )
  )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用ggplot2我会这样做

library(ggplot2)
CUTOFF <- 1
df$color <- ifelse(df$y > CUTOFF, "green", "red")
ggplot(df, aes(xmin = x - 0.5, xmax = x + 0.5,
               ymin = CUTOFF, ymax = y, fill = I(color))) +
  geom_rect()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ste*_*fan 5

实现所需结果的一种选择是使用带有一些辅助列的堆积条形图。基本上,我使用一个透明的底部栏,在其顶部添加两个栏,反映截止值下方和上方的值。

注意:我必须将该x列转换为因子,否则我会得到一个最大为 20 的 x 轴。

library(echarts4r)
library(dplyr)

set.seed(1)

df <- data.frame(
  x = 1:10,
  y = 1 + cumsum(rnorm(10, 0, 0.1))
)

df |> 
  mutate(x = factor(x),
         bottom = ifelse(y < 1, y, 1),
         lt = ifelse(y < 1, 1 - y, 0),
         gte = ifelse(y < 1, 0, y - 1)) |>
  e_charts(x) |> 
  e_bar(bottom, stack = "x", itemStyle = list(color = "transparent", barBorderColor  = "transparent"), legend = FALSE) |>
  e_bar(lt, stack = "x") |> 
  e_bar(gte, stack = "x") |> 
  e_color(c("red", "green"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述