R语言可视化(三十二):金字塔图绘制

32. 金字塔图绘制


清除当前环境中的变量

rm(list=ls())

设置工作目录

setwd("C:/Users/Dell/Desktop/R_Plots/32pyramid/")

使用plotrix包绘制人口金字塔图

# 安装并加载所需的R包
#install.packages("plotrix")
library(plotrix)

# 构建示例数据
xy.pop<-c(3.2,3.5,3.6,3.6,3.5,3.5,3.9,3.7,3.9,3.5,
          3.2,2.8,2.2,1.8,1.5,1.3,0.7,0.4)
xx.pop<-c(3.2,3.4,3.5,3.5,3.5,3.7,4,3.8,3.9,3.6,3.2,
          2.5,2,1.7,1.5,1.3,1,0.8)
agelabels<-c("0-4","5-9","10-14","15-19","20-24","25-29","30-34",
             "35-39","40-44","45-49","50-54","55-59","60-64",
             "65-69","70-74","75-79","80-44","85+")
mcol<-color.gradient(c(0,0,0.5,1),c(0,0,0.5,1),c(1,1,0.5,1),18)
fcol<-color.gradient(c(1,1,0.5,1),c(0.5,0.5,0.5,1),c(0.5,0.5,0.5,1),18)
head(xy.pop)
## [1] 3.2 3.5 3.6 3.6 3.5 3.5

head(xx.pop)
## [1] 3.2 3.4 3.5 3.5 3.5 3.7

head(agelabels)
## [1] "0-4"   "5-9"   "10-14" "15-19" "20-24" "25-29"

head(mcol)
## [1] "#0000FFFF" "#0000FFFF" "#0000FFFF" "#0000FFFF" "#0000FFFF" "#0000FFFF"

head(fcol)
## [1] "#FF8080FF" "#FF8080FF" "#FF8080FF" "#FF8080FF" "#FF8080FF" "#FF8080FF"

# 使用pyramid.plot函数绘制人口金字塔图
par(mar=pyramid.plot(xy.pop,xx.pop,labels=agelabels,
                     main="Australian population pyramid 2002",
                     lxcol=mcol,rxcol=fcol,
                     gap=0.5,show.values=TRUE))
image.png
# three column matrices
avtemp<-c(seq(11,2,by=-1),rep(2:6,each=2),seq(11,2,by=-1))
malecook<-matrix(avtemp+sample(-2:2,30,TRUE),ncol=3)
femalecook<-matrix(avtemp+sample(-2:2,30,TRUE),ncol=3)
# group by age
agegrps<-c("0-10","11-20","21-30","31-40","41-50","51-60",
           "61-70","71-80","81-90","91+")
head(malecook)
##      [,1] [,2] [,3]
## [1,]   13    0   11
## [2,]   11    0   10
## [3,]    9    1    9
## [4,]   10    3   10
## [5,]    5    4    7
## [6,]    8    4    6

head(femalecook)
##      [,1] [,2] [,3]
## [1,]   12    0   13
## [2,]    9    2   10
## [3,]   11    1   10
## [4,]    7    4   10
## [5,]    6    4    6
## [6,]    7    6    7

head(agegrps)
## [1] "0-10"  "11-20" "21-30" "31-40" "41-50" "51-60"

oldmar<-pyramid.plot(malecook,femalecook,labels=agegrps,
                     unit="Bowls per month",
                     lxcol=c("#ff0000","#eeee88","#0000ff"),
                     rxcol=c("#ff0000","#eeee88","#0000ff"),
                     laxlab=c(0,10,20,30),
                     raxlab=c(0,10,20,30),
                     top.labels=c("Males","Age","Females"),
                     gap=4,
                     do.first="plot_bg(\"#eedd55\")")
# give it a title
mtext("Porridge temperature by age and sex of bear",3,2,cex=1.5)
# stick in a legend
legend(par("usr")[1],11,legend = c("Too hot","Just right","Too cold"),
       fill=c("#ff0000","#eeee88","#0000ff"))
# don't forget to restore the margins and background
par(mar=oldmar,bg="transparent")
image.png

使用DescTools包绘制人金字塔图

# 安装并加载所需的R包
#install.packages("DescTools")
library(DescTools)

# 构建示例数据
d.sda <- data.frame(
  kt_x =  c("ZH","BL","ZG","SG","LU","AR","SO","GL","SZ",
            "NW","TG","UR","AI","OW","GR","BE","SH","AG",
            "BS","FR","GE","JU","NE","TI","VD","VS"),
  apo_n = c(18,16,13,11,9,12,11,8,9,8,11,9,7,9,24,19,
            19,20,43,27,41,31,37,62,38,39),
  sda_n = c(235,209,200,169,166,164,162,146,128,127,
            125,121,121,110,48,34,33,0,0,0,0,0,0,0,0,0)
)
head(d.sda)
##   kt_x apo_n sda_n
## 1   ZH    18   235
## 2   BL    16   209
## 3   ZG    13   200
## 4   SG    11   169
## 5   LU     9   166
## 6   AR    12   164

# 使用PlotPyramid函数绘制人口金字塔图
PlotPyramid(lx=d.sda[,"apo_n"], 
            rx=d.sda[,"sda_n"],
            ylab=d.sda$kt_x,
            col=c("lightslategray", "orange2"),
            border = NA, ylab.x=0,
            xlim=c(-110,250),
            gapwidth = NULL, 
            cex.lab = 0.8, cex.axis=0.8, 
            xaxt = TRUE,
            lxlab="Drugstores", 
            rxlab="General practitioners",
            main="Density of general practitioners and drugstores in CH (2010)",
            space=0.5, args.grid=list(lty=1))
image.png
op <- par(mfrow=c(1,3))
m.pop<-c(3.2,3.5,3.6,3.6,3.5,3.5,3.9,3.7,3.9,3.5,
         3.2,2.8,2.2,1.8,1.5,1.3,0.7,0.4)
f.pop<-c(3.2,3.4,3.5,3.5,3.5,3.7,4,3.8,3.9,3.6,3.2,
         2.5,2,1.7,1.5,1.3,1,0.8)
age <- c("0-4","5-9","10-14","15-19","20-24","25-29",
         "30-34","35-39","40-44","45-49","50-54",
         "55-59","60-64","65-69","70-74","75-79","80-44","85+")
# 查看数据
head(m.pop)
## [1] 3.2 3.5 3.6 3.6 3.5 3.5

head(f.pop)
## [1] 3.2 3.4 3.5 3.5 3.5 3.7

head(age)
## [1] "0-4"   "5-9"   "10-14" "15-19" "20-24" "25-29"

# 左侧图
PlotPyramid(m.pop, f.pop,
            ylab = age, space = 0, 
            col = c("cornflowerblue", "indianred"),
            main="Age distribution at baseline of HELP study",
            lxlab="male", rxlab="female" )
# 中间图
PlotPyramid(m.pop, f.pop,
            ylab = age, space = 1, 
            col = c("blue", "red"),
            xlim=c(-5,5),
            main="Age distribution at baseline of HELP study",
            lxlab="male", rxlab="female", 
            gapwidth=0, ylab.x=-5 )
# 右侧图
PlotPyramid(c(1,3,5,2,0.5), c(2,4,6,1,0),
            ylab = LETTERS[1:5], space = 0.3, 
            col = rep(rainbow(5), each=2),
            xlim=c(-10,10), args.grid=NA, 
            cex.names=1.5, adj=1,
            lxlab="Group A", rxlab="Group B", 
            gapwidth=1, ylab.x=-8, xaxt="n")
par(op)
image.png

使用ggplot2包绘制金字塔图

library(ggplot2)
library(plyr)

# 构建示例数据
mov <-c(23.2,33.5,43.6,33.6,43.5,43.5,43.9,33.7,53.9,43.5,
        43.2,42.8,22.2,51.8,41.5,31.3,60.7,50.4)
mob<-c(13.2,9.4,13.5,13.5,13.5,23.7,8,3.18,3.9,3.16,23.2,
       22.5,22,12.7,12.5,12.3,10,0.8)
fov<-c(13.2,9.4,13.5,13.5,13.5,23.7,8,3.18,3.9,3.16,23.2,
       22.5,22,12.7,12.5,12.3,10,0.8)
fob<-c(23.2,33.5,43.6,33.6,43.5,23.5,33.9,33.7,23.9,43.5,
       18.2,22.8,22.2,31.8,25.5,25.3,31.7,28.4)
labs<-c("uk","scotland","france","ireland","germany","sweden","norway",
        "iceland","portugal","austria","switzerland","australia",
        "new zealand","dubai","south africa","finland","italy","morocco")

df = data.frame(labs=rep(labs,4), values=c(mov, mob, fov, fob), 
                sex=rep(c("Male", "Female"), each=2*length(fov)),
                bmi = rep(rep(c("Overweight", "Obese"), each=length(fov)),2))
head(df)
##       labs values  sex        bmi
## 1       uk   23.2 Male Overweight
## 2 scotland   33.5 Male Overweight
## 3   france   43.6 Male Overweight
## 4  ireland   33.6 Male Overweight
## 5  germany   43.5 Male Overweight
## 6   sweden   43.5 Male Overweight

# Order countries by overall percent overweight/obese
labs.order = ddply(df, .(labs), summarise, sum=sum(values))
labs.order = labs.order$labs[order(labs.order$sum,decreasing = T)]
# 设置因子进行排序
df$labs = factor(df$labs, levels=labs.order)

# 绘制金字塔图
ggplot(df, aes(x=labs)) +
  geom_bar(data=subset(df,sex=="Male"), aes(y=values, fill=bmi), stat="identity") +
  geom_bar(data=subset(df,sex=="Female"), aes(y=-values, fill=bmi), stat="identity") +
  geom_hline(yintercept=0, colour="white", lwd=2) +
  theme_bw()+
  coord_flip(ylim=c(-100,100)) + 
  scale_fill_brewer(palette='Set1') +
  scale_y_continuous(breaks=seq(-100,100,50), labels=c(100,50,0,50,100)) +
  labs(y="Percent", x="Country") +
  ggtitle("Female                   Male") +
  theme(plot.title = element_text(hjust = 0.5))
image.png
sessionInfo()
## R version 3.6.0 (2019-04-26)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 18363)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936 
## [2] LC_CTYPE=Chinese (Simplified)_China.936   
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C                              
## [5] LC_TIME=Chinese (Simplified)_China.936    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] plyr_1.8.4        ggplot2_3.2.0     DescTools_0.99.38 plotrix_3.7-6    
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.5         RColorBrewer_1.1-2 compiler_3.6.0    
##  [4] pillar_1.4.2       class_7.3-15       tools_3.6.0       
##  [7] boot_1.3-23        digest_0.6.20      lifecycle_0.2.0   
## [10] evaluate_0.14      tibble_2.1.3       rootSolve_1.8.2.1 
## [13] gtable_0.3.0       lattice_0.20-38    pkgconfig_2.0.2   
## [16] rlang_0.4.7        Matrix_1.2-17      rstudioapi_0.10   
## [19] yaml_2.2.0         mvtnorm_1.0-11     expm_0.999-5      
## [22] xfun_0.8           e1071_1.7-4        withr_2.1.2       
## [25] dplyr_1.0.2        stringr_1.4.0      knitr_1.23        
## [28] generics_0.0.2     vctrs_0.3.2        tidyselect_1.1.0  
## [31] gld_2.6.2          grid_3.6.0         glue_1.4.2        
## [34] R6_2.4.0           lmom_2.8           rmarkdown_1.13    
## [37] purrr_0.3.2        magrittr_1.5       scales_1.0.0      
## [40] htmltools_0.3.6    MASS_7.3-51.4      Exact_2.1         
## [43] colorspace_1.4-1   stringi_1.4.3      lazyeval_0.2.2    
## [46] munsell_0.5.0      crayon_1.3.4
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,601评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,367评论 1 305
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,249评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,539评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,967评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,929评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,098评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,825评论 0 207
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,609评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,796评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,282评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,603评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,277评论 3 242
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,159评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,959评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,079评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,874评论 2 277