tidyverse / tidyverse/ggplot2

Add option to jitter outliers in a boxplot

Open
#4,480 1 comment 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature layers :chart_with_upwards_trend:
Dominant language
R
Stars
7k
Forks
2.1k
Avg merge
59m
Merged PRs (30d)
2

Description

I would like to be able to add a small amount of jittering to outliers in a boxplot or alternatively stack the points to avoid having them overlap.

Here is an example of where points in a boxplot overlap:

library(ggplot2)
library(dplyr)

# outliers are overlapping
ggplot(mpg, aes(drv, cty)) +
  geom_boxplot()

To add jittering to these outliers, we currently have to result to the following hack, by creating a separate dataset of outliers and plotting them using geom_jitter() manually.

# adding jittering to outliers is a bit of work
outliers <- 
  mpg %>%
  group_by(drv) %>%
  filter(cty > quantile(cty, 0.75) + 1.5 * IQR(cty) | 
           cty < quantile(cty, 0.25) - 1.5 * IQR(cty))

ggplot(mpg, aes(drv, cty)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(height = 0, width = 0.1, data = outliers)

I understand that the position argument in geom_boxplot() is already "occupied", so maybe the simplest solution would probably to just add a new argument outlier.jitter = c(0, 0) (for x and y coordinate jittering respectively).

An even better solution would of course be to incorporate the beeswarm algorithm from ggbeeswarm:


library(ggbeeswarm)

ggplot(mpg, aes(drv, cty)) +
  geom_boxplot(outlier.shape = NA) +
  geom_beeswarm(data = outliers)

Created on 2021-05-17 by the reprex package (v2.0.0)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no repository files or tests; start by tracing geom_boxplot() and its existing position argument, using the provided geom_jitter() workaround as the behavioral reference. Determine whether the requested behavior should be jittering, stacking, or both, and consider how the option would work for boxplot outliers without a separate dataset.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
data-visualization
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.