对,就是瀑布图,你没看错。而且是使用ggplot现有图层叠加构造,并没有用任何ggplot的外挂插件。
作图理念是在数据源的构造上,方法与《Excel图表之道》《Excel图表拒绝平庸》中的方法一致,我只是加入了自己的技巧。
library("reshape2") library("ggplot2") library("ggmap") library("Cairo")
构造瀑布图数据源:
Item<-c("Before","Factor A","Factor B","Factor C","Factor D","Factor E","Factor F","Factor G","After") Data<-c(325,-32,-105,38,86,97,232,389,1030) mydata<-data.frame(Item,Data,stringsAsFactors =F) mydata$BA<-mydata$Data mydata$Dummy<-0 mydata$add<-0 mydata$Reduc<-0 mydata$BA[2:8]<-0
for (i in 2:8){ ifelse(mydata$Data[i]<0,mydata$Dummy[i]<-sum(mydata$Data[1:i]),mydata$Dummy[i]<-sum(mydata$Data[1:i-1])) } for (i in 2:8){ ifelse(mydata$Data[i]<0,mydata$add[i]<-0,mydata$add[i]<-mydata$Data[i]) } for (i in 2:8){ ifelse(mydata$Data[i]<0,mydata$Reduc[i]<-abs(mydata$Data[i]),mydata$add[i]<-0) }
mydata1<-mydata[,-2] mydataA<- melt(mydata1,id.vars ="Item",variable.name = "class", value.name = "scope")
mydataA$class<-factor(mydataA$class,levels=c("Reduc","add","Dummy","BA"),order=T)
色盘设置:
Color<-c("#A6442A","#015313","#FFFFFF","#131F37")
作图函数:
CairoPNG(file="C:/Users/Administrator/Desktop/瀑布图1.png",width=650,height=360) ggplot()+ geom_bar(data=mydataA,aes(x=Item,y=scope,fill=class),stat="identity",position="stack",width=1)+ scale_x_discrete(limits=Item)+ scale_fill_manual(values=Color)+ guides(fill=FALSE)+ geom_text(data=mydata1,aes(x=Item,y=BA/2),label=ifelse(mydata1$BA!=0,mydata1$BA,""),col="white")+ geom_text(data=mydata1,aes(x=Item,y=Dummy+add),label=ifelse(mydata1$add!=0,paste("+",mydata1$add,sep=""),""),col="#015313",vjust=-.5)+ geom_text(data=mydata1,aes(x=Item,y=Dummy),label=ifelse(mydata1$Reduc!=0,paste("-",mydata1$Reduc,sep=""),""),col="#A6442A",vjust=1.2)+ theme( panel.background=element_blank(), axis.title=element_blank(), axis.text = element_text(colour ="black",size=12,face="italic"), axis.text.y=element_blank(), axis.ticks=element_blank() ) dev.off()
通过角度旋转,得到水平方向瀑布图:
CairoPNG(file="C:/Users/Administrator/Desktop/瀑布图2.png",width=650,height=360) ggplot()+ geom_bar(data=mydataA,aes(x=Item,y=scope,fill=class),stat="identity",position="stack",width=1)+ scale_x_discrete(limits=Item)+ scale_fill_manual(values=Color)+ coord_flip()+ guides(fill=FALSE)+ geom_text(data=mydata1,aes(x=Item,y=BA/2),label=ifelse(mydata1$BA!=0,mydata1$BA,""),col="white")+ geom_text(data=mydata1,aes(x=Item,y=Dummy+add),label=ifelse(mydata1$add!=0,paste("+",mydata1$add,sep=""),""),col="#015313",hjust=-.20)+ geom_text(data=mydata1,aes(x=Item,y=Dummy),label=ifelse(mydata1$Reduc!=0,paste("-",mydata1$Reduc,sep=""),""),col="#A6442A",hjust=1.2)+ theme( panel.background=element_blank(), axis.title=element_blank(), axis.text = element_text(colour ="black",size=12,face="italic"), axis.text.x=element_blank(), axis.ticks=element_blank() ) dev.off()
核心要点总结: