I'm struggling to maintain color consistency across charts while ordering geom_bar() based on another value.
Desired:
Actual:
library(tidyverse)
dat <- data.frame(x = c("A","B"), y = c(1,2), z = c(4,3))
# Y
dat %>%
mutate(x = fct_reorder(x, y,`.desc` = TRUE)) %>%
ggplot(aes(x = x, y = y, fill = x)) +
geom_bar(stat = "identity")
# Z
dat %>%
mutate(x = fct_reorder(x, z,`.desc` = TRUE)) %>%
ggplot(aes(x = x, y = z, fill = x)) +
geom_bar(stat = "identity")
Created on 2020-08-31 by the reprex package (v0.3.0)
This approach ended up working for me:
dat %>%
arrange(desc(z)) %>%
ggplot(aes(x = reorder(x, desc(z)), y = z, fill = x)) +
geom_bar(stat = "identity")