Home > Software design >  R: How to modify bars ordering in barchart - ggplot?
R: How to modify bars ordering in barchart - ggplot?

Time:08-21

On ggplot bars are ordered automatically according to Budget within each category. Now I want to order them manually, and set in the following order: C, A, B

library(tidyr)
library(dplyr)
library(ggplot2)

df <- structure(list(Way = c("In", "In", "In", "In", 
"In", "Out", "Out", "Out", "Out", "Out"), 
    Cat2 = structure(c(1L, 2L, 2L, 3L, 3L, 1L, 2L, 2L, 3L, 
    3L), levels = c("C", "A", "B"), class = "factor"), 
    Budget = c(-56, 17, -61, 18, -9, -24, 18, 
    -40, 6, -32), Cat1 = c("C", "Plus", 
    "Minus", "Plus", "Minus", "C", "Plus", 
    "Minus", "Plus", "Minus")), row.names = c(NA, 
-10L), class = "data.frame")


df %>%
  mutate(y = tidytext::reorder_within(Cat2, Budget, Way)) %>%
  group_by(Cat2, Way) %>%
  mutate(Budget_neg = sum(Budget[Budget < 0])) %>%
  ggplot(aes(Budget, y, fill = Cat2, color = Cat2))  
  geom_col(position = "stack")  
  geom_col(position = 'identity', aes(x = Budget_neg), fill = 'white')  
  tidytext::scale_y_reordered()  
  labs(fill = "Cat2")  
  facet_grid(Way ~ ., switch = "y",scales = "free_y")  
  theme(axis.text.x = element_text(angle = 90),
        strip.background = element_rect(fill = "white"),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(0, "lines"))   
  theme(legend.position="none") 
  labs( y = " ")   geom_vline(xintercept = 0,linetype="dotted", color="white")

enter image description here

CodePudding user response:

You could remove your first mutate and create your "Cat2" column as a factor with the right order in the levels argument like this:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>%
  #mutate(y = tidytext::reorder_within(Cat2, Budget, Way)) %>%
  group_by(Cat2, Way) %>%
  mutate(Budget_neg = sum(Budget[Budget < 0])) %>%
  ggplot(aes(Budget, factor(Cat2, levels = c("B", "A", "C")), fill = Cat2, color = Cat2))  
  geom_col(position = "stack")  
  geom_col(position = 'identity', aes(x = Budget_neg), fill = 'white')  
  tidytext::scale_y_reordered()  
  labs(fill = "Cat2")  
  facet_grid(Way ~ ., switch = "y",scales = "free_y")  
  theme(axis.text.x = element_text(angle = 90),
        strip.background = element_rect(fill = "white"),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(0, "lines"))   
  theme(legend.position="none") 
  labs( y = " ")   geom_vline(xintercept = 0,linetype="dotted", color="white")

Created on 2022-08-21 with reprex v2.0.2

As you can see the order is: C, A, B.

  • Related