Aligning subsets of data with ggplot2

I am trying to create a complex shape that overlays individual data points on a box in order to display both the final statistics and the variance of the raw data. I have 2 questions in an important order:

  • How to center the flickering dots around the middle of their respective window section?
  • How to remove dark dots from drv legend?

the code:

library(ggplot2)
library(dplyr)

mpg$cyl <- as.factor(mpg$cyl)

mpg %>% filter(fl=="p" | fl=="r" & cyl!="5") %>% sample_n(100) %>% ggplot(aes(cyl, hwy, fill=drv)) + 
  stat_boxplot(geom = "errorbar", width=0.5, position = position_dodge(1)) +
  geom_boxplot(position = position_dodge(1), outlier.shape = NA)+
  geom_point(aes(fill=drv, shape=fl), color="black", show.legend=TRUE, alpha=0.5, size=3, position = position_jitterdodge(dodge.width = 1)) +
  scale_shape_manual(values = c(21,23))

Example figure

+4
source share
1 answer

It appears that the current evasion for is geom_pointbased on fillboth and shape. Use groupto indicate that you only want to dodge drv.

You can use override.aesin guide_legendto remove points from the legend fill.

mpg %>%
    filter(fl=="p" | fl=="r" & cyl!="5") %>% 
    sample_n(100) %>%
    ggplot(aes(cyl, hwy, fill=drv)) +
      stat_boxplot(geom = "errorbar", width=0.5, position = position_dodge(1)) +
      geom_boxplot(position = position_dodge(1), outlier.shape = NA)+
      geom_point(aes(fill = drv, shape = fl, group = drv), color="black", 
                 alpha  =0.5, size=3, 
                 position = position_jitterdodge(jitter.width = .1, dodge.width = 1)) +
      scale_shape_manual (values = c(21,23) ) +
      guides(fill = guide_legend(override.aes = list(shape = NA) ) )

enter image description here

+5
source

Source: https://habr.com/ru/post/1684481/


All Articles