jKraut
jKraut

Reputation: 2487

Custom Legend Order in Echarts4r

Working with echarts4r and attempting to get a custom order in my scatter plot. Echarts4r appears to ALWAYS sort these categories alphabetically. I even tried e_charts(x, reorder = FALSE) %>% per this post. Looking for help to custom order these?

 output$plot1 <- renderEcharts4r({

     df <- data.frame(
      cats = c("catb", "cata", "catc"),
      x = c(1, .5, .75),
      y = c(.5,.2, 0)
    )

      p <- df %>%
        mutate(x = x - 0.5,
               y = y - 0.5) %>%
        group_by(cats) %>%

        e_charts() %>%
        e_effect_scatter(y,),
        ) %>%
        e_text_style(color = 'white') %>%
        e_x_axis(name='', nameLocation='center', 
                 axisLine = list(show = TRUE, lineStyle=list(color='#666', width=2)), min = -0.5, max = 0.5,
                 axisTick = list(show = FALSE), axisLabel = list(show = FALSE), splitLine=list(lineStyle=list(color='#333')), margin = c(0.5, 0.1)) %>%
        e_y_axis(name='', nameLocation='center', 
                 axisLine = list(show = TRUE, lineStyle=list(color='#666', width=2)), min = -0.5, max = 0.5,
                 axisTick = list(show = FALSE), axisLabel = list(show = FALSE), splitLine=list(lineStyle=list(color='#333')), margin = c(0.5, 0.1)) %>%
        e_legend(textStyle = list(color = 'white')) %>%
        e_color(color = c('#53a662', '#343ee8', '#eda65b')) 
    p
  })

output plot: notice how categories get reordered

Upvotes: 0

Views: 909

Answers (1)

stefan
stefan

Reputation: 124183

One option to get a custom order would be to convert your cats column to a factor with the levels set in your desired order:

library(echarts4r)
library(dplyr)

df %>%
  mutate(
    x = x - 0.5,
    y = y - 0.5,
    cats = factor(cats, levels = c("catc", "cata", "catb"))
  ) %>%
  group_by(cats) %>%
  e_charts() %>%
  e_effect_scatter(y) %>%
  e_text_style(color = "white") %>%
  e_x_axis(
    name = "", nameLocation = "center",
    axisLine = list(show = TRUE, lineStyle = list(color = "#666", width = 2)), min = -0.5, max = 0.5,
    axisTick = list(show = FALSE), axisLabel = list(show = FALSE), splitLine = list(lineStyle = list(color = "#333")), margin = c(0.5, 0.1)
  ) %>%
  e_y_axis(
    name = "", nameLocation = "center",
    axisLine = list(show = TRUE, lineStyle = list(color = "#666", width = 2)), min = -0.5, max = 0.5,
    axisTick = list(show = FALSE), axisLabel = list(show = FALSE), splitLine = list(lineStyle = list(color = "#333")), margin = c(0.5, 0.1)
  ) %>%
  #e_legend(textStyle = list(color = "white")) %>%
  e_color(color = c("#53a662", "#343ee8", "#eda65b"))

enter image description here

Upvotes: 2

Related Questions