我正在尝试按顺序绘制垂直堆积条形图,如下所示。
这是我用过的代码。
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
答案 0 :(得分:0)
#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")