Skip to content

Instantly share code, notes, and snippets.

@jennybc
Created March 30, 2020 05:21
Show Gist options
  • Save jennybc/847c6b43c4e35cec2e5bb30a3f38af73 to your computer and use it in GitHub Desktop.
Save jennybc/847c6b43c4e35cec2e5bb30a3f38af73 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)
@songxxiao
Copy link

really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment