Search code examples
rdplyrecharts4r

echarts4r pie chart highlight colour


I have a dataset in a similar format to the below. I would like to highlight the "blue_wedge" class in one colour (e.g., blue) and for all other wedges (in this example "2nd" and "3rd" classes) to share a second colour (e.g., "grey") -- helping me better highlight the proportion of "deaths" for whatever the "blue_wedge" value happens to be.

Titanic <- as.data.frame(Titanic)

blue_wedge <- "1st"

Titanic %>% 
  filter(Class %in% c('1st','2nd','3rd')) %>% 
  group_by(Class) %>% 
  summarise(People = sum(Freq)) %>% 
  e_charts(Class) %>%  
  e_pie(People, radius = c("50%", "70%"), legend = FALSE)

I have tried looking at other similar questions (e.g., How to set fixed colors for each value in echarts4r?), but haven't had any success so far. Any help really appreciated.

Thanks


Solution

  • Here is one option to create a vector of colors which could then be used in e_color to achieve your desired result:

    library(echarts4r)
    library(dplyr, warn = FALSE)
    
    cols <- rep("grey", nlevels(factor(Titanic$Class)))
    cols[levels(factor(Titanic$Class)) == blue_wedge] <- "blue"
    
    Titanic %>%
      filter(Class %in% c("1st", "2nd", "3rd")) %>%
      group_by(Class) %>%
      summarise(People = sum(Freq)) %>%
      e_charts(Class) %>%
      e_pie(People, radius = c("50%", "70%"), legend = FALSE) %>%
      e_color(color = cols)
    

    enter image description here