Skip to content

Instantly share code, notes, and snippets.

@TonyLadson
Forked from jennybc/2020-03-29_sane-legend.R
Created April 11, 2020 07:41
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 TonyLadson/c31192b6e8ae6726d7bc516dfd8bcaa9 to your computer and use it in GitHub Desktop.
Save TonyLadson/c31192b6e8ae6726d7bc516dfd8bcaa9 to your computer and use it in GitHub Desktop.
Make the legend order = data order, with forcats::fct_reorder2()
library(tidyverse)
library(patchwork)
dat_wide <- tibble(
x = 1:3,
top = c(4.5, 4, 5.5),
middle = c(4, 4.75, 5),
bottom = c(3.5, 3.75, 4.5)
)
dat <- dat_wide %>%
pivot_longer(
cols = c(top, middle, bottom),
names_to = "region",
values_to = "awfulness") %>%
mutate(
region_ABCD = factor(region),
region_sane = fct_reorder2(region, x, awfulness)
)
p_ABCD <- ggplot(dat, aes(x, awfulness, colour = region_ABCD)) +
geom_line() + theme(legend.justification = c(1, 0.85))
p_sane <- ggplot(dat, aes(x, awfulness, colour = region_sane)) +
geom_line() + theme(legend.justification = c(1, 0.85))
p <- p_ABCD + p_sane +
plot_annotation(
title = 'Make the legend order = data order, with forcats::fct_reorder2()')
ggsave("foo.png", p, width = 16, height = 9, scale = 0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment