在ggplot中订购堆叠条形图 [英] Order Stacked Bar Graph in ggplot
问题描述
我的同事和我正试图根据y值排序堆积条形图,而不是按x值按字母顺序排列。
My colleague and I are trying to order a stacked bar graph based on the y-values instead of alphabetically by the x-values.
示例数据为:
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))
我想绘制一张堆积的条形图。我一直在这样做:
I want to graph this has a stacked bar graph. I have been doing this with:
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)的总和来排序,而不是按姓名的字母顺序排序。
But I ultimately want to sort by the sum of the 4 variables (I, S, D, and C) instead of the alphabetical order of the fullnames.
非常感谢任何帮助!谢谢!!
Any help is greatly appreciated! Thank you!!
推荐答案
一般(非 ggplot
- 特定)答案是使用 reorder()
来重置分类列中的因子级别,这是基于其他列的某些功能。
The general (non ggplot
-specific) answer is to use reorder()
to reset the factor levels in a categorical column, based on some function of the other columns.
## 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)
<然后只是使用原始问题的代码重新绘制。
Then just replot, using code from the original question
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")
< img src =https://i.stack.imgur.com/wnNGn.pngalt =在这里输入图片描述>
这篇关于在ggplot中订购堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!