1

I've been struggling for a few hours to change the order of stacked bar chart.

I looked at two SO threads: How to change stacking order in stacked bar chart in R? and How to control ordering of stacked bar chart using identity on ggplot2

Both of these threads use rev() function in factor(). However, for some reason, this doesn't work for me.

Here's my code: (The version in which "D" appears at the top in bar and in legend)

a<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(1,2,3,4)))
b<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(4,3,2,1)))
d<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(5,8,9,10)))

a$type <- c("A")
b$type <- c("B")
d$type <- c("d")
c<-rbind(a,b,d)
c$type <- factor(c$type,levels = rev(c$type))

windows()
ggplot(data = c, aes(x = ID, y = Num, fill = type)) + 
  geom_bar(stat = "identity")

Now, I want to reverse this by having "A" at the top both in the bar chart and in the legend. I tried this code:

a<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(1,2,3,4)))
b<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(4,3,2,1)))
d<-as.data.frame(list(ID=c("Q1","Q2","Q3","Q4"),Num = c(5,8,9,10)))

a$type <- c("A")
b$type <- c("B")
d$type <- c("d")
c<-rbind(a,b,d)
c$type <- factor(c$type,levels = c$type)



windows()
ggplot(data = c, aes(x = ID, y = Num, fill = type)) + 
  geom_bar(stat = "identity")

This reverses the order in the legend but not the order in the bar chart. I still see the order D-> B -> A. I am really frustrated.

Can someone please help me? I'd appreciate your thoughts.

Community
  • 1
  • 1
watchtower
  • 4,140
  • 14
  • 50
  • 92
  • Use `unique` to get rid of duplicate levels, or you'll run into problems. To clean up: `c$type <- droplevels(c$type)` – alistaire Aug 23 '16 at 00:05
  • Alistaire, Thanks for your help. I added the code mentioned by you. However, ggplots still spits out D, B and A. Could you please help me ? Do you want me to post the code? – watchtower Aug 23 '16 at 00:11
  • 1
    Ok. It seems that I need to sort the data first. Here's the thread I looked at: http://stackoverflow.com/questions/32345923/how-to-control-ordering-of-stacked-bar-chart-using-identity-on-ggplot2?noredirect=1&lq=1. Here's the code I used: c<-c[order(c$type, decreasing = T),] This fixed the issue. – watchtower Aug 23 '16 at 00:17
  • 4
    Part of the confusion is that ggplot2's behavior has changed in recent versions. For a long time, setting the factor level order worked, but now you need to sort the data frame. – joran Aug 23 '16 at 01:16
  • @joran That should be an answer. – Brandon Bertelsen Jan 20 '17 at 01:14

0 Answers0