如何使用ggplot()来排列堆叠的垂直条?
问题描述:
我试图按照如下方式以有序的方式绘制垂直堆叠的条形图。 如何使用ggplot()来排列堆叠的垂直条?
这是我用过的代码。
setwd('d:/Dataset/lynda')
unitcounts<-read.csv('ucounts.csv',header=T,sep=',')
library(reshape2)
prodf<-melt(unitcounts,id.var = "Units")
attach(prodf)
library(ggplot2)
ggplot(prodf,aes(x=Units,y=value,fill=variable))+geom_bar(stat="identity")
prodf
这是我得到的输出。有人可以帮助我有序地安排垂直栏吗?
Units,Person1,Person2,Person3,Person4,Person5
Whatsits,54,64,31,43,47
Doohickeys,28,47,21,28,32
Gadgets,23,34,14,19,28
Bahbooms,0,0,0,0,0
Heehaws,0,0,0,0,0
Doodads,0,0,0,0,0
Meemaws,13,20,11,15,15
Watchamacalists,22,30,15,15,19
答
#calculate total
unitcounts$total <- rowSums(unitcounts[,-1])
#reorder factor levels by total
unitcounts$Units <- factor(unitcounts$Units, levels=unitcounts$Units[order(unitcounts$total)])
#include total in id.vars, doesn't need to be plotted
prodf<-melt(unitcounts,id.var = c("Units","total"))
ggplot(prodf,aes(x=Units,y=value,fill=variable))+geom_bar(stat="identity")
+0
非常感谢Heroka和其他人。它工作正常。感谢所有的努力 –
你的帮助是非常赞赏和欢迎。我正在尝试从过去4小时这个简单的事情。请帮助我 –
请将数据放入问题主体(编辑按钮)。 – tonytonov
我不清楚你在问什么?你想改变图例的顺序(从人5到人1而不是1到5)?或者你想改变你的X轴(称为单位)的安排? – mts