Conditional color for bar chart
Hi,
given the following mini-example:
df <- data.frame(
name = LETTERS[1:5]
, loss = sample(1:20, 5)
, country = c("BRA", "COL", "BRA", "HND", "BRA")
)
plot_e <- df %>%
echarts4r::e_charts(x = name) %>%
echarts4r::e_bar(serie = loss)
plot_e
Is there a convenient way to color the bars dependend on country? I tried echarts4r::e_visual_map(serie = country), but then the plot is empty. I think the argument serie needs numerical values.
In the above example, I could use case_when or ifelse to add a column with color values or something like that. But my productive data set is a large geodata set with many different countries, so that way would be quite laborious. :-)
Second question: Making a lollipop chart using echarts4r, is there a better way besides using e_bar combined with e_scatter?
Thanks for help!
Answer to first question on how to associate color to column content (country).
library(dplyr); library(echarts4r)
df <- data.frame(
name = LETTERS[1:5]
, loss = sample(1:20, 5)
, country = c("BRA", "COL", "BRA", "HND", "BRA")
)
myColors <- c("#387e78", "#eeb422", "#d9534f")
df <- df |> rowwise() |> mutate(color= myColors[unique(df$country)==country])
plot_e <- df %>%
e_charts(x = name) %>%
e_bar(serie = loss) %>%
e_add_nested("itemStyle", color)
plot_e

Regarding second question: maybe you can experiment with drawing lines (e_line()) and symbol (circle) with width larger than the width of the line.
Thanks! :-)