Change the order of Stacked Bar Chart in ggplot2

2019-08-04 11:42发布

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.

标签: r ggplot2
0条回答
登录 后发表回答