Search code examples
rechartsecharts4r

How I can show the labels on echarts4r plot but just every 2 or 3 bars?


Hi and thanks for reading me. Im working on a echarts plot in R and I want to show the label of the vars but only in every 2 or 3 bars, because i don't want it to look too saturated with information

I haven't found a working argument to e_labels(), could someone help me?

My code is the following:

library(echarts4r)

mtcars |> 
  tibble::rownames_to_column("model") |> 
  e_charts(model) |> 
  e_bar(cyl) |> 
  e_legend(F) |> 
  e_labels()

Solution

  • I think a good way to do it with mtcars is to create a label column which contains text when the value in cyl is different to the previous row. We can then bind the label to the bar as set out in this answer.

    mtcars |>
        tibble::rownames_to_column("model") |>
        dplyr::mutate(
            cyl_changed = cyl != dplyr::lag(cyl, default = TRUE),
            label = ifelse(cyl_changed, cyl, "")
        ) |>
        e_charts(model) |>
        e_bar(
            cyl,
            bind = label,
            label = list(
                show = TRUE,
                formatter = "{b}",
                position = "outside"
            )
        ) |>
        e_legend(F)
    

    enter image description here

    If your real data doesn't have this property you can create a label every three rows, e.g:

        dplyr::mutate(
            label = ifelse(
                dplyr::row_number() %% 3 == 0,
                as.character(cyl),
                ""
            )
        )