为了账号安全,请及时绑定邮箱和手机立即绑定

ggplot中的订单堆积条形图

ggplot中的订单堆积条形图

PIPIONE 2019-12-04 10:13:07
我和我的同事正在尝试根据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)的总和而不是全名的字母顺序进行排序。任何帮助是极大的赞赏!谢谢!!
查看完整描述

2 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

通用(非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")


查看完整回答
反对 回复 2019-12-04
  • 2 回答
  • 0 关注
  • 564 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信