1

I want to plot a pie chart and give each value a fixed color. Give the e_color() function a named list does unfourtunately not work. Any suggestions?

library(tibble)
library(echarts4r)

tibble(class=c("A", "B"), n=c(34,12)) %>%
e_charts(class) %>%
e_pie(n) %>%
e_color(color = c("A" = "red", "B" = "yellow"))

Note: I use the pie chart in a shiny app where the values for class can take on different values depending on user input. Sometimes only class A occurs, sometimes A,B,C and so on, whereby the colors of the different values of class should always remain the same.

werN
  • 109
  • 7

2 Answers2

2

This should work

tibble(class=c("A", "B"), n=c(34,12)) %>%
e_charts(class) %>%
e_pie(n) %>%
e_color(color = c("red", "yellow"))

Edit: you can create a data frame with a colour for each class and depending on the value for class you will get a fixed colour

df_colours <- data.frame(class = LETTERS[1:4],
                         colours = c("red", "yellow", "blue", "green"))

df <- tibble(class=c("A", "B"), n=c(34,12))

colour <- df_colours %>%
  filter(class %in% df$class) %>%
  select(colours) %>%
  unlist() %>% 
  unname()


df %>%
  e_charts(class) %>%
  e_pie(n) %>%
  e_color(color = colour)
mmw
  • 138
  • 8
  • That works for this case, but I use the pie chart in a shiny app where the values for `class` can take on different values depending on user input. Sometimes only class A occurs, sometimes A,B,C and so on, whereby the colors of the different values of `class` should always remain the same. – werN Nov 04 '21 at 12:10
1

As an addition to @mmw's answer, you probably want to give a named vector for colors (which afaik is not possible at the moment using echarts4r). A workaround for this is the following code:

# define a vector of colors
vec_colors <- c("green1" = "green", "blue1" = "blue", "red1" = "red")

# values
df <- tibble(x = c(1, 2, 1, 2, 1, 2),
             class = c("green1", "green1", "red1", "red1", "blue1", "blue1"),
             n=c(10, 20, 5, 7, 12, 8))

# by default echarts4r sorts the legend alphabetically, hence sort
cols <- unname(vec_colors[sort(unique(df$class))])

df %>%
  group_by(class) |> 
  e_charts(x) %>%
  e_line(n) %>%
  e_color(color = cols)

enter image description here

David
  • 9,216
  • 4
  • 45
  • 78