金字塔图

作者

[编辑] 郑虎;

[审核] .

注记

Hiplot 网站

本页面为 Hiplot Pyramid Chart 插件的源码版本教程,您也可以使用 Hiplot 网站实现无代码绘图,更多信息请查看以下链接:

https://hiplot.cn/basic/pyramid-chart?lang=zh_cn

金字塔图是一种将数据分布于中轴两侧类似金字塔的图形。

环境配置

  • 系统: Cross-platform (Linux/MacOS/Windows)

  • 编程语言: R

  • 依赖包: ggcharts

# 安装包
if (!requireNamespace("ggcharts", quietly = TRUE)) {
  install.packages("ggcharts")
}

# 加载包
library(ggcharts)

数据准备

载入数据为年龄段,性别分类及前两种变量组合后的人口数目。

# 加载数据
data <- read.delim("files/Hiplot/144-pyramid-chart-data.txt", header = T)

# 查看数据
head(data)
    age    sex    pop
1   0-4   male 225817
2   0-4 female 213072
3   5-9   male 223656
4   5-9 female 210508
5 10-14   male 214782
6 10-14 female 201672

可视化

# 金字塔图
p <- pyramid_chart(data = data, x = age, y = pop, group = sex, 
                   title = "", sort = "no", bar_colors = c("#C20B01","#196ABD")) +
  theme(text = element_text(family = "Arial"),
        plot.title = element_text(size = 12,hjust = 0.5),
        axis.title = element_text(size = 12),
        axis.text = element_text(size = 10),
        axis.text.x = element_text(angle = 0, hjust = 0.5,vjust = 1),
        legend.position = "right",
        legend.direction = "vertical",
        legend.title = element_text(size = 10),
        legend.text = element_text(size = 10))

p
图 1: 金字塔图

图示将年龄段按照顺序从下到上依次显示在中轴线上,左侧表示男性人数,右侧表示女性人数,x 轴表示人口数量,该图可以很明显看出男女在不同年龄段的人数占比情况以及相同性别中不同年龄组的占比情况。