Search code examples
rechartsecharts4r

Waterfall chart on echarts4r?


Hi and thanks for reading me I'm working with a bar chart on R with the Echarts4r package, but I want to do a waterfall chart and I don't find an option to do a plot like the following on the image: enter image description here

It's possible to do this chart type? The code I'm using for now is the following:

library(echarts4r)

df <- data.frame(
  
  var = sample(LETTERS, 5),
  value = rnorm(5, mean = 200, sd = 100)
)


df |> 
  e_charts(var) |> 
  e_bar(value)

Solution

  • Not sure whether echarts4r offers an option out of the box but with some data wrangling you could achieve your result as a stacked bar chart like so:

    Disclaimer: I borrowed the basic idea from here.

    library(echarts4r)
    library(dplyr)
    
    set.seed(42)
    
    df <- data.frame(
      var = sample(LETTERS, 5),
      value = rnorm(5, mean = 200, sd = 100)
    )
    
    df |> 
      mutate(bottom = cumsum(dplyr::lag(value, default = 0)),
             bottom = ifelse(value < 0, bottom + value, bottom),
             top = abs(value)) |>
      e_charts(var) |> 
      e_bar(bottom, stack = "var", itemStyle = list(color = "transparent", barBorderColor  = "transparent")) |>
      e_bar(top, stack = "var")
    

    enter image description here