我已经挣扎了几个小时来改变堆积条形图的顺序。
我查看了两个SO主题:How to change stacking order in stacked bar chart in R?和How to control ordering of stacked bar chart using identity on ggplot2
这两个线程都在factor()中使用rev()函数。但是,出于某种原因,这对我来说并不起作用。
这是我的代码: (" D"出现在条形图和图例顶部的版本)
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")
现在,我希望通过让#34; A&#34;在条形图和图例中的顶部。 我试过这段代码:
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")
这会反转图例中的顺序,但不会反转条形图中的顺序。我仍然看到订单D-> B - &gt;答:我真的很沮丧。
有人可以帮帮我吗?我很感激你的想法。