ggplot中的订单堆积条形图

我和我的同事正在尝试根据y值而不是按x值按字母顺序排列堆积的条形图。


样本数据是:


samp.data <- structure(list(fullname = c("LJ", "PR", 

"JB", "AA", "NS", 

"MJ", "FT", "DA", "DR", 

"AB", "BA", "RJ", "BA2", 

"AR", "GG", "RA", "DK", 

"DA2", "BJ2", "BK", "HN", 

"WA2", "AE2", "JJ2"), I = c(2L, 

1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 3L, 3L, 

3L, 3L, 3L, 3L, 3L, 3L, 3L), S = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 

2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 3L, 

3L), D = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 

2L, 2L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 3L), C = c(0L, 2L, 1L, 

2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 

2L, 3L, 3L, 3L, 3L)), .Names = c("fullname", "I", "S", "D", "C"

), class = "data.frame", row.names = c(NA, 24L))

我想绘制一个堆积的条形图。我一直在这样做:


md <- melt(samp.data, id=(c("fullname")))

temp.plot<-ggplot(data=md, aes(x=fullname, y=value, fill=variable) ) + geom_bar()+ opts(axis.text.x=theme_text(angle=90))+ opts(title = "Score Distribtion")

ggsave(temp.plot,filename="test.png")

但是我最终希望按4个变量(I,S,D和C)的总和而不是全名的字母顺序进行排序。


任何帮助是极大的赞赏!谢谢!!


PIPIONE
浏览 608回答 2
2回答

慕容3067478

通用(非ggplot特定)答案是reorder()根据其他列的某些功能来重置类别列中的因子水平。## Examine the default factor orderlevels(samp.data$fullname)## Reorder fullname based on the the sum of the other columnssamp.data$fullname <- reorder(samp.data$fullname, rowSums(samp.data[-1]))## Examine the new factor orderlevels(samp.data$fullname)attributes(samp.data$fullname)然后使用原始问题中的代码重新绘制md <- melt(samp.data, id=(c("fullname")))temp.plot<-ggplot(data=md, aes(x=fullname, y=value, fill=variable) ) +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;geom_bar()+&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;theme(axis.text.x=theme_text(angle=90)) +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;labs(title = "Score Distribtion")## ggsave(temp.plot,filename="test.png")
打开App,查看更多内容
随时随地看视频慕课网APP