1

I have a stacked bar chart and I want to add a value label above each stacked bar. I don't want values for each section of the stack.

This yields a value for each section of the stack:


library(echarts4r)

set.seed(1)

d <- data.frame(
  xaxis = c(rep("a", 2), rep("b", 2)),
  groups  = c("c", "d", "c", "d"),
  value = rnorm(4, mean = 50)
)

d |>
  group_by(groups) |>
  e_chart(xaxis) |>
  e_bar(value, stack = "grp1") |>
  e_labels()

enter image description here

I just want one number above each bar, equal to the sum of each section.

Giovanni Colitti
  • 1,982
  • 11
  • 24

1 Answers1

3

You can precalculate the labels of your groups and then bind them to e_bar :

library(echarts4r)
set.seed(1)

d <- data.frame(
   xaxis = c(rep("a", 2), rep("b", 2)),
   groups  = c("c", "d", "c", "d"),
   value = rnorm(4, mean = 50)
   ) |>
   group_by(xaxis) |>
   dplyr::mutate(Label = ifelse(groups == "c","",as.character(sum(value))))

d |>
  group_by(groups) |>
  e_chart(xaxis) |>
  e_bar(value, stack = "groups",
     bind = Label,
     label = list(
       show = TRUE,
       formatter = "{b}",
       position = "outside"
     )
  ) 
Thor6
  • 781
  • 6
  • 9
  • Thank you! Does the `b` in `formatter = "{b}"` stand for "bind" and thus references the bound data? – Giovanni Colitti Oct 21 '22 at 17:07
  • 1
    not exactly, "bind" adds a name argument to the data and with {b} you can reference it. other options are also available : https://echarts.apache.org/en/option.html#series-bar.label.formatter – Thor6 Oct 22 '22 at 12:07