Search code examples
rboxplotechartsecharts4r

Echarts4r + Boxplot + Jitter points: How to make this combination work properly?


How to make this combination work? I can create the boxplot. I can create a scatter plot with jittered points, but I cannot put them together. Does anyone have any idea? The idea is to continue using echarts library.

library(echarts4r)
library(dplyr)

echart1 <- mtcars |>
  group_by(cyl) |>
  e_charts(cyl) |>
  e_scatter_(
    "hp",
    jitter_factor = 2
  ) 

echart2 <- mtcars |>
  group_by(cyl) |>
  e_charts() |>
  e_boxplot(hp)

Solution

  • Not sure if it helps after so much time has passed, but I just ran across your question.

    The reason it isn't working in any way that may be considered obvious is because echarts always categorizes the grouping axis when creating a box plot. When you have a scatter plot, you need two numerical axes for it to be meaningful. The great news here is that you can still do this, you just need to "explain" it to echarts.

    Let's start with your boxplot, that provides the look you want (for example, the x-axis does not start at zero). Now, since you are going to jitter the points, I suggest that you don't plot the outliers.

    Next is adding the jitter plot. You'll need to assign it to a different x-axis. The first is "0", so assign it to "1". Then tell echarts how to restrain that axis (e.g., don't start at 0) and here you can hide this new axis.

    I made the scatter points large to make them obvious.

    Starting with that plot you had for the boxplot...

    library(tidyverse)
    library(echarts4r)
    
    mtcars %>% 
      group_by(cyl) %>% 
      e_charts(cyl) %>% 
      e_boxplot(hp, outliers = F) %>%  # <--turning outlier plotting off
      e_scatter(hp, jitter_factor = 2, symbol_size = 10, # <-- made points HUGE
                x_index = 1,     # <---- give it a new x-axis
                legend = F) %>%  # <---- no legends please
      e_x_axis(index = 1, min = 3, max = 9, # confine to 3 <-> 9
               show = F)                    # don't show axis
    

    enter image description here