仿经济学人——矩阵气泡图

时间:2022-05-08
本文章向大家介绍仿经济学人——矩阵气泡图,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本篇文章案例来源于经济学人2013年一幅关于家庭支出结构与国家间的交叉对比图。

该图信息量相当丰富,至少涵盖了四个维度的信息,支出结构信息(类别型字段)、国别信息(类别型字段)、支出水平分类(类别型字段)、支出规模(数值型指标)等。

倘若使用ggplot进行绘制,思路非常简单,仅通过散点图层皆可完成,ggplot2的散点图可以支持离散标度,但是如果想要处理好类别的顺序,需要把类别型变量因子化。

因为原图中有奖金100+数据点,很多都没有具体数值,一个一个用肉眼估计简直丧心病狂,所以我模拟了一组数值,只保证思路讲到位就OK。

setwd("E:/微信公众号/公众号——数据小魔方/2017年9月/20170914/")
mydata<-read.csv("matrix_bubble.csv",stringsAsFactors = FALSE,check.names = FALSE)

原始数据中带有n,导入时R语言会自动给添加一个,这里涉及到R语言中保留字符的问题,需要将多余的删掉。

mydata$Class[c(1,6,7)]<-c("Housing,fueln&utilities","Restaurantsn& hotels","Clothingn& footwear")
names(mydata)[9:11]<-c("SaudinArabia","SouthnKorea","UnitednStates")library("tidyr")
mydata1<-gather(mydata,Country,Spend,-1)
mydata1$Class<-factor(mydata1$Class,levels=c("Education","Alcohol & tobacco","Communications","Furnishings","Clothingn& footwear","Restaurantsn& hotels","Health","Recreation","Transport","Food","Housing,fueln&utilities"),ordered=T)

分割支出规模的类别区间:

qa<-quantile(mydata1$Spend,c(0,.25,.5,.75,1))
mydata1$Spend_fact<-cut(mydata1$Spend,breaks=qa,labels = c("lowest spend","below average","above average","highest spend"),include.lowest=TRUE,ordered=T)

制作草图:

library("ggplot2")library("grid")library("showtext")library("Cairo")
font.add("myfont","msyh.ttc")
setwd("E:/《R语言商务图表与可视化》/9.12——R语言ggplot2可视化在线分享")
CairoPNG(file="matirx_scatter.png",width=1200,height=900)
showtext.begin()
ggplot(data=mydata1)+

geom_hline(aes(x=Country,y=Class,yintercept = 1:nrow(mydata1)),size=20,colour="#E4EDF2",alpha=.5)+
geom_vline(aes(x=Country,y=Class,xintercept = 1:nrow(mydata1)),linetype="dashed")+
geom_point(aes(x=Country,y=Class,size=Spend,fill=Spend_fact),shape=21,colour="white")+
scale_fill_manual(values=c("#F9DBD3","#F1B255","#519F46","#41B0C3"))+
scale_size_area(max_size=25)+
scale_x_discrete(position = "top")+
guides(size=FALSE,fill=guide_legend(title="Within category",direction="horizontal"))+
labs(title="How they spend it",subtitle="Househlod spending*,of total,2013 or latest,includes taxes",caption="Source:Eurostat")+
theme_void(base_size=20,base_family="myfont") %+replace%
theme(
      legend.position="top",
      panel.grid.major.x=element_line(linetype="dashed"),      #plot.margin=margin(5,5,5,5,unit="pt"),
      axis.text=element_text(size=15,hjust=0.5),
      plot.title=element_text(size=35,hjust=0,lineheight=1.2),
      plot.caption=element_text(hjust=0,lineheight=1.2)
) 
showtext.end()
dev.off()

数据源请移步GitHub主页下载: https://github.com/ljtyduyu/DataWarehouse/tree/master/File