1

I have created a stacked histogram in ggplot. I would like to change the order of the stacked bars.

My dataset looks like this:

head(df)
  difficulty RegularPool SuperPool Item_Pool
1    -3.1185           1        NA   Regular
2    -2.9385           1        NA   Regular
3    -2.8100           1        NA   Regular
4    -2.2797           1        NA   Regular
5    -3.3321           1        NA   Regular
6    -3.0996           1        NA   Regular

I create the ggplot:

ggplot(data = df, 
    aes(x = difficulty, color = Item_Pool, fill = Item_Pool)) +
    geom_histogram(alpha= 0.5, position = "stack", binwidth = 0.1) +
    geom_vline(xintercept = logit.placement, linetype = "dashed", color = "blue") + #add placement lines
    annotate("text", x = logit.placement, y = 0, angle = 45, label=c("One Below", "Early","Mid", "Late", "One Above"), colour = "blue") + #label placement lines
    xlim(-8, 7) +
    ylab("Number of Testlets") +
    xlab("Testlet Difficulty") +
    ggtitle(paste("Grade ", grade, " Overall Cut = ", item.pool.cut, sep = ""))  

enter image description here

How can I get the blue ("Super") bars to be on top of the red ("Regular") bars?

Kate N
  • 423
  • 3
  • 14
  • 1
    Possible duplicate of [Order categorical data in a stacked bar plot with ggplot2](https://stackoverflow.com/questions/7150453/order-categorical-data-in-a-stacked-bar-plot-with-ggplot2) – camille Oct 01 '19 at 01:55
  • Also related: https://stackoverflow.com/q/48188780/5325862, https://stackoverflow.com/q/15251816/5325862, https://stackoverflow.com/q/5208679/5325862 – camille Oct 01 '19 at 01:58

1 Answers1

1

You can change the orders of the factors in df before calling ggplot

df$Item_Pool = factor(df$Item_Pool,levels=c("Super","Regular"))

Put the levels in the order you need

fmarm
  • 4,209
  • 1
  • 17
  • 29