Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@jennybc

This comment has been minimized.

Copy link
Owner Author

@jennybc jennybc commented Mar 30, 2020

foo

@songxxiao

This comment has been minimized.

Copy link

@songxxiao songxxiao commented Apr 11, 2020

really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.