JohnCoene / echarts4r

🐳 ECharts 5 for R
http://echarts4r.john-coene.com/
Other
595 stars 81 forks source link

Conditional color for bar chart #456

Open svenb78 opened 2 years ago

svenb78 commented 2 years ago

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!

helgasoft commented 2 years ago

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

rdatasculptor commented 2 years ago

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

svenb78 commented 2 years ago

Thanks! :-)