原文地址:https://mp.weixin.qq.com/s/Iz9GR6hE2vIlziH_y7npew
一个小案例,使用ggplot2绘制蝴蝶图,在巩固温习条形图坐标轴翻转的同时,重新熟悉一下如何利用grid系统进行版式布局。
原图如下:
该图表思路很简单,就是两个条形图通过坐标轴翻转,使用grid包中的版式布局函数进行合理的版式拼接即可。
以下是整个案例代码部分,因为涉及到的知识点不复杂,这里不做详细注释:
第一部分:制作右侧的柱形图:
#导入工具包:
library("ggplot2")
library("dplyr")
library("grid")
library("showtext")
library("Cairo")font.add("myfont","msyh.ttc")
#生成图形所需数据集:
mydata<-data.frame(id=1:14,A=c(5.0,14.7,2.5,8.5,5.1,6.9,7.7,6.8,4.4,4.9,5.3,1.0,0.9,7.8),B=c(31.3,24.7,17.8,17.2,15.3,14.3,13.9,13.9,12.4,10.0,6.5,4.2,2.5,0.9),Label=c("Website","Customer & Employee Referral","Webinar","Facebook/Twitter/Other Social","Marketting & Advertising","Paid Serch","Other","Sales generated","Tradeshows","Parter","Linkedin","Events","Lead list","Emial Campaign"))
p1<-ggplot(mydata)+geom_hline(yintercept=mean(mydata$A),linetype=2,size=.25,colour="grey")+geom_bar(aes(x=id,y=A),stat="identity",fill="#E2BB1E",colour=NA)+ylim(-5.5,16)+scale_x_reverse()+geom_text(aes(x=id,y=-4,label=Label),vjust=.5)+geom_text(aes(x=id,y=A+.75,label=paste0(A,"%")),size=4.5,family="myfont",fontface="bold")+coord_flip()+theme_void();p1
#图一:
第二部:制作左侧柱形图:
p2<-ggplot(mydata)+geom_hline(yintercept=-mean(mydata$B),linetype=2,size=.25,colour="grey")+geom_bar(aes(x=id,y=-B),stat="identity",fill="#C44E4C",colour=NA)+ylim(-40,0)+scale_x_reverse()+geom_text(aes(x=id,y=-B-1.75,label=paste0(B,"%")),size=4.5,family="myfont",fontface="bold")+coord_flip()+theme_void();p2
#图二效果
图形整合:
setwd("E:/数据可视化/R/R语言学习笔记/数据可视化/ggplot2/优秀R语言案例")CairoPNG(file="butterfly.png",width=1200,height=696)showtext.begin()grid.newpage()pushViewport(viewport(layout=grid.layout(7,11)))vplayout<-function(x,y){viewport(layout.pos.row =x,layout.pos.col=y)}print(p2,vp=vplayout(2:7,1:5))print(p1,vp=vplayout(2:7,6:11))grid.text(label="Opportunity-to-Deal\nConversion Rate",x=.80,y=.88,gp=gpar(col="black",fontsize=15,fontfamily="myfzhzh",draw=TRUE,just="centre"))grid.text(label="Lead-to-Opportunity\nConversion Rate",x=.20,y=.88,gp=gpar(col="black",fontsize=15,fontfamily="myfzhzh",draw=TRUE,just="centre"))grid.text(label="Webinars convert opportunities,but don't close",x=.50,y=.95,gp=gpar(col="black",fontsize=20,fontfamily="myfzhzh",draw=TRUE,just="centre"))showtext.end()dev.off()
注意以上代码中所使用的coord_flip函数、geom_text函数以及最后的grid系列函数的用法。