iris1<-melt(iris, id.vars='Species', measure.vars=c('Sepal.Length','Sepal.Width','Petal.Length','Petal.Width'))
iris1<-data.table(iris1)
iris1_1<-iris1[,list(sumvalue=sum(value)),by=list(Species,variable)]
setorder(iris1_1,Species)
#设置标签的高度,累计的高度为堆叠上面的一半
iris1_2<-iris1_1[,label_y:=cumsum(sumvalue)-sumvalue/2,by=list(Species)]
ggplot(iris1_2,aes(x=factor(Species, levels=levels(iris1_2$Species)[c(3,2,1)]), y=sumvalue, fill=factor(variable,levels=levels(iris1_2$variable)[c(4,3,2,1)])))+
geom_bar(stat='identity',position=position_dodge())+ #本来不用reverse是从上到下,反过来
theme1+
geom_text(aes(x=Species,y=sumvalue+20,label=sumvalue, color=factor(variable, levels=levels(iris1_2$variable)[c(4,3,2,1)])),#和fill的一致
position=position_dodge(width=0.9),show.legend = F)+#showlegend 隐藏文字的图例
ggtitle('柱状图')+
scale_fill_discrete(name='图例', #图例项(或者用scale_fill_discrete)
labels=levels(iris1_2$variable)[c(4,3,2,1)])+
#颜色 scale_x_discrete(name='类别', #x轴坐标名称
labels=levels(iris1_2$Species)[c(3,2,1)])+ #离散的标签
scale_y_continuous(name='值', #y轴坐标名称
breaks=seq(0,400,50),limits=c(0,400))#连续的标签和坐标轴