Skip to content

Instantly share code, notes, and snippets.

@jonspring
Created October 25, 2020 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonspring/4e12787a6f0a95ec3ed03f0314f84987 to your computer and use it in GitHub Desktop.
Save jonspring/4e12787a6f0a95ec3ed03f0314f84987 to your computer and use it in GitHub Desktop.
library(tidyverse)
example_df <- tribble(
~Year, ~Category, ~Name,
2015, "A", "1",
2015, "A", "3",
2015, "A", "5",
2015, "C", "2",
2015, "C", "4",
2016, "A", "1",
2016, "A", "4",
2016, "B", "2",
2016, "B", "3",
2016, "B", "5",
2017, "B", "1",
2017, "B", "2",
2017, "B", "3",
2017, "B", "4",
2017, "C", "5",
2018, "B", "1",
2018, "B", "2",
2018, "B", "3",
2018, "B", "4",
2018, "B", "5"
) %>%
mutate(Year = factor(Year))
max_group = example_df %>%
count(Year, Category) %>%
pull(n) %>%
max
grid_width = ceiling(max_group^0.5)
grid_height = ceiling(max_group / grid_width)
example_df_grid <- example_df %>%
group_by(Year, Category) %>%
arrange(Name) %>%
mutate(nudge_x = ((row_number() - 1) %% grid_width / (grid_width - 1)) * 0.2,
nudge_y = -((row_number() - 1) %/% grid_width) / grid_height * 0.3) %>%
ungroup()
ggplot(example_df_grid,
aes(x = Year,
y = fct_rev(Category),
color = Name)) +
geom_point(size = 3,
position = position_nudge(x = example_df_grid$nudge_x,
y = example_df_grid$nudge_y)) +
labs(title = "No jittering; overplotting") +
theme(legend.position = "bottom")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment