Search code examples
rggplot2forcats

Maintain consistent colors while changing geom_bar order?


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)


Solution

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