Maintain consistent colors while changing geom_bar order?

111 Views Asked by At

I'm struggling to maintain color consistency across charts while ordering geom_bar() based on another value.

Desired:

  • A & B colors remain consistent between charts
  • Each plot has descending order of A & B

Actual:

  • A & B swap colors between charts
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)

1

There are 1 best solutions below

0
user2579689 On BEST ANSWER

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")