订购ggplot中的堆积条形图

时间:2011-11-18 17:30:02

标签: r ggplot2

我的同事和我正在尝试根据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)的总和而不是全名的字母顺序排序。

非常感谢任何帮助!谢谢!!

1 个答案:

答案 0 :(得分: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")

enter image description here