echarts4r icon indicating copy to clipboard operation
echarts4r copied to clipboard

Conditional color for bar chart

Open svenb78 opened this issue 3 years ago • 3 comments

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!

svenb78 avatar Aug 30 '22 17:08 svenb78

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

image

helgasoft avatar Aug 31 '22 02:08 helgasoft

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

rdatasculptor avatar Sep 01 '22 18:09 rdatasculptor

Thanks! :-)

svenb78 avatar Sep 07 '22 23:09 svenb78