1

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()
  • You cross posted this question. Another solution was mentioned here https://github.com/JohnCoene/echarts4r/issues/516#issuecomment-1510244601. please close the issue on GitHub. Thanks! – rdatasculptor Apr 24 '23 at 20:38

2 Answers2

1

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),
            ""
        )
    )
SamR
  • 8,826
  • 3
  • 11
  • 33
0

Another approach would be not using formatter but doing it like this with the help of e_add_nested():

library(echarts4r)
library(dplyr)

df <- mtcars |> 
  tibble::rownames_to_column("model") |> arrange(model)
df$show <- rep(c(TRUE, FALSE, FALSE), 
               length.out = nrow(df))

df |> 
  e_charts(model) |> 
  e_bar(cyl, label = list(position = "insideTop")) |> 
  e_add_nested("label", show) |>
  e_legend(F)
rdatasculptor
  • 8,112
  • 14
  • 56
  • 81