我的同事和我正在尝试根据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)的总和而不是全名的字母顺序排序.
任何帮助是极大的赞赏!谢谢!!
Jos*_*ien 22
一般(非ggplot特定)答案是用于reorder()根据其他列的某些功能重置分类列中的因子级别.
## Examine the default factor order
levels(samp.data$fullname)
## Reorder fullname based on the the sum of the other columns
samp.data$fullname <- reorder(samp.data$fullname, rowSums(samp.data[-1]))
## Examine the new factor order
levels(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) ) + 
               geom_bar()+ 
               theme(axis.text.x=theme_text(angle=90)) + 
               labs(title = "Score Distribtion")
## ggsave(temp.plot,filename="test.png")

| 归档时间: | 
 | 
| 查看次数: | 25109 次 | 
| 最近记录: |