1

I am trying to reorder the stacks in geom_bar, such that "Time frame 1" is closer to the x axis (see below). I have looked at other similar posts in SO, and they suggest reordering the data frame in order to reorder the stacks. However this has not worked for me, I was wondering if there were any other ways.

Here is a reproducible example:

name <- c("A", "B", "C", "A", "B", "C")
variable <- c("Time frame 1", "Time frame 1", "Time frame 1", "Time frame 2", "Time frame 2", "Time frame 2")
value <- rnorm(6, 20, 8)

practicedf <- data.frame(name, variable, value)

ggplot(data = rbind(pdf2, pdf1), mapping = aes(x = name, y = value, fill = variable)) + geom_bar(stat = "identity")

This gives the following result:

Instead of this order, I want time frame 1 to be closer to the x axis

Instead of this order, I want time frame 1 to be closer to the x axis

As I mentioned earlier, I read that changing the order of the data frame can achieve this. Below is what I tried, however it was unsuccessful, producing the exact same plot. Below is the code:

pdf1 <- practicedf[1:3,]
pdf2 <- practicedf[4:6,]
revpdf <- rbind(pdf2, pdf1)

ggplot(data = revpdf, mapping = aes(x = name, y = value, fill = variable)) + geom_bar(stat = "identity")
lmo
  • 37,904
  • 9
  • 56
  • 69
  • 2
    Just for the reference: https://stackoverflow.com/questions/32345923/how-to-control-ordering-of-stacked-bar-chart-using-identity-on-ggplot2 – M-- Jul 24 '17 at 20:37
  • 5
    Yup, it's not about manually reordering the data structure. If you are using character variable it's sorted alphabetically. So you need to convert it into factor with levels ordering of your choice. In your case `variable <- factor(variable, levels = c("Time frame 2", "Time frame 1"))`. – zielinskipp Jul 24 '17 at 20:46

0 Answers0