0

Goal:

Plot stat_summary points with full opacity over box plots with variable alpha.

MWE:

################################################################################
# !Important!
# Assume that `palette1` is already defined, and shared between multiple figures
################################################################################
ncols = length(unique(mtcars$gear))
palette1 = scales::hue_pal()(ncols)
names(palette1) = sort(unique(mtcars$gear))
p = ggplot(mtcars, aes(x=as.factor(gear), y=mpg,fill=as.factor(gear),alpha=as.factor(cyl))) + 
      geom_boxplot() +
      scale_alpha_discrete(range = c(0.1, 0.8),guide = guide_legend(override.aes = list(fill = "black"))) +
      rotate_x_text(45) +
      facet_grid(~gear,scale="free") +
      stat_summary(fun=mean, geom="point", shape=5, size=5,position = position_dodge(.75),stroke=1.5)

set_palette(p, palette1)

Current Behavior:

The reduced opacity of stat_summary points makes them hard to see.

enter image description here

mkk
  • 879
  • 6
  • 19
  • To get a grey scale for the `alpha` legend see https://stackoverflow.com/a/69508613/12993861. To align the points add `position = position_dodge(.75)` to `stat_summary`. See e.g. https://stackoverflow.com/a/68040424/12993861. – stefan Oct 20 '21 at 06:00
  • Thanks, @stefan for your excellent posts which I have also upvoted. I have revised the OP to implement all your suggestions, and highlight the remaining issue which is visibility of the `stat_summary` points. – mkk Oct 20 '21 at 17:45

1 Answers1

0

Note:

This answer implements corrections suggested by @stefan in comments to the original post.

p2 = ggplot(mtcars,aes(x=as.factor(gear), y=mpg,fill=as.factor(gear))) + 
      geom_boxplot(aes(x=as.factor(gear), y=mpg,fill=as.factor(gear),alpha=as.factor(cyl))) +
      scale_alpha_discrete(range = c(0.1, 0.8),guide = guide_legend(override.aes = list(fill = "black"))) +
      rotate_x_text(45) +
      facet_grid(~gear,scale="free") +
      stat_summary(fun=mean, geom="point", shape=18, size=5,
                      aes(group=as.factor(cyl),x=as.factor(gear), y=mpg),
                      position = position_dodge(.75),stroke=1.5)

set_palette(p2, palette1)

enter image description here

mkk
  • 879
  • 6
  • 19