0

I found posts like How to control ordering of stacked bar chart using identity on ggplot2 where the order of factors can be re-leveled when the bar plots have the same factors in them, or using a numeric to order the stacked bars, but I want to create a stacked bar plots where each stack has its own unique factors.

test <- data.frame(unique_factors = c("stack", "bars", "in", "this", "exact", "order"),
           length = c(1,5,3,2,6,1),
           groups = c("1", "1", "1", "2", "2", "2"))

ggplot(test, aes(x = groups, y = length)) +
  geom_bar(stat = "identity", aes(fill = unique_factors, levels=c("stack", "bars", "in", "this", "exact", "order")))

Current Output

enter image description here

Desired Output

enter image description here

Is it possible to achieve this effect - if so, how? Thank you so much for your help!

tjebo
  • 21,977
  • 7
  • 58
  • 94
MayaGans
  • 1,815
  • 9
  • 30
  • Hi @RonakShah, I'm sorry but I'm unsure what you're asking - I'm using the `groups` as the x-axis for my repex here and would like to stack each group by the `unique_factors` – MayaGans Jan 02 '20 at 04:09

2 Answers2

1

You could also have used the forcats package:

fct_inorder puts them in the order we have in our data.frame and fct_rev reverses the ordering:

library(forcats)
ggplot(test, aes(x = groups, y = length)) +
  geom_bar(stat = "identity",
           aes(fill = fct_rev(fct_inorder(unique_factors))))

enter image description here

Chris
  • 3,836
  • 1
  • 16
  • 34
0

I just needed to refactor the unique_factors!

test$unique_factors <- factor(test$unique_factors, levels = c("stack", "bars", "in", "this", "exact", "order"))
MayaGans
  • 1,815
  • 9
  • 30
  • 1
    which can be also done with `test$unique_factors <- factor(test$unique_factors, levels = unique(test$unique_factors))` instead of typing them all out. – Ronak Shah Jan 02 '20 at 04:23