美文网首页
R语言|绘制金字塔图

R语言|绘制金字塔图

作者: 维凡生物 | 来源:发表于2021-09-24 09:20 被阅读0次

前言

金字塔图典型的是人口金字塔图,人口金字塔是用类似古埃及金字塔的形象描绘人口年龄和性别分布状况的图形,能表明人口现状及其发展类型。当有类似的信息需要表达时,即可用金字塔图来呈现。以下有两种绘图方法,可供参考。

** PART01**
1.导入plotrix包

library(plotrix)

2.构建示例数据

m.pop <- runif(18,0,4)
f.pop <- runif(18,0,4)

3.分组

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+")

4.颜色区分

mcol <- color.gradient(c(1,0,0.4,2),c(0,1,0.4,2),c(1,1,0.4,1),18)
fcol <- color.gradient(c(1,1,0.5,1),c(1,1,0.5,1),c(1,0.5,0.6,1),18)

5.查看构建示例数据前六行

head(m.pop)
head(f.pop)
head(agelabels)
head(mcol)
head(fcol)

6.使用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))

** PART02**

1.构建数据

library(plotrix)
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)

2.按年龄分组

agegrps<-c("0-10","11-20","21-30","31-40","41-50","51-60",
           "61-70","71-80","81-90","91+")

3.查看构建数据的前六行

head(malecook)
head(femalecook)
head(agegrps)

4.使用pyramid.plot函数绘制人口金字塔图

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\")")

5.添加标题

mtext("Porridge temperature by age and sex of bear",3,2,cex=1.5)

6.添加注释信息

legend(par("usr")[1],11,legend = c("Too hot","Just right","Too cold"),
            fill=c("#ff0000","#eeee88","#0000ff"))

7.为添加的注释信息添加图形的空白边界行数和背景颜色(想要查看到图形变化需要再运行一下注释信息)

par(mar=oldmar,bg="white")

以上就是关于金字塔图的画法分享啦!

相关文章

网友评论

      本文标题:R语言|绘制金字塔图

      本文链接:https://www.haomeiwen.com/subject/fkingltx.html