# 安装包
if (!requireNamespace("data.table", quietly = TRUE)) {
install.packages("data.table")
}
if (!requireNamespace("jsonlite", quietly = TRUE)) {
install.packages("jsonlite")
}
if (!requireNamespace("plotrix", quietly = TRUE)) {
install.packages("plotrix")
}
if (!requireNamespace("ggplotify", quietly = TRUE)) {
install.packages("ggplotify")
}
# 加载包
library(data.table)
library(jsonlite)
library(plotrix)
library(ggplotify)金字塔堆叠图2
注记
Hiplot 网站
本页面为 Hiplot Pyramid Stack2 插件的源码版本教程,您也可以使用 Hiplot 网站实现无代码绘图,更多信息请查看以下链接:
金字塔堆叠图可以用于展示年龄组多变量。
环境配置
系统: Cross-platform (Linux/MacOS/Windows)
编程语言: R
依赖包:
data.table;jsonlite;plotrix;ggplotify
sessioninfo::session_info("attached")─ Session info ───────────────────────────────────────────────────────────────
setting value
version R version 4.5.2 (2025-10-31)
os Ubuntu 24.04.3 LTS
system x86_64, linux-gnu
ui X11
language (EN)
collate C.UTF-8
ctype C.UTF-8
tz UTC
date 2026-01-18
pandoc 3.1.3 @ /usr/bin/ (via rmarkdown)
quarto 1.8.27 @ /usr/local/bin/quarto
─ Packages ───────────────────────────────────────────────────────────────────
package * version date (UTC) lib source
data.table * 1.18.0 2025-12-24 [1] RSPM
ggplotify * 0.1.3 2025-09-20 [1] RSPM
jsonlite * 2.0.0 2025-03-27 [1] RSPM
plotrix * 3.8-13 2025-11-15 [1] RSPM
[1] /home/runner/work/_temp/Library
[2] /opt/R/4.5.2/lib/R/site-library
[3] /opt/R/4.5.2/lib/R/library
* ── Packages attached to the search path.
──────────────────────────────────────────────────────────────────────────────
数据准备
# 加载数据
data <- data.table::fread(jsonlite::read_json("https://hiplot.cn/ui/basic/pyramid-stack2/data.json")$exampleData$textarea[[1]])
data <- as.data.frame(data)
# 整理数据格式
agegrps <- unique(data[,1])
split_var <- unique(data[,2])
dat_left <- as.matrix(data[data[,2] == split_var[1],-c(1,2)])
dat_right <- as.matrix(data[data[,2] == split_var[2],-c(1,2)])
# 查看数据
head(data) Month Year Class1 Class2 Class3 Class4
1 1 2019 8 6.0 8 6.0
2 2 2019 4 2.0 4 2.0
3 3 2019 4 4.5 1 4.5
4 4 2019 6 8.0 1 9.0
5 5 2019 8 6.0 8 6.0
6 6 2019 4 2.0 4 2.0
可视化
# 金字塔堆叠图2
p <- as.ggplot(function() {
cols <- c("#E64B35FF","#4DBBD5FF","#00A087FF","#3C5488FF")
names(cols) <- colnames(dat_left)
cols <- cols[1:ncol(dat_left)]
pyramid.plot(dat_left, dat_right, labels = agegrps, unit = "Value",
lxcol = cols, rxcol = cols,
laxlab=as.numeric(c(0,10,20,30)), raxlab=as.numeric(c(0,10,20,30)),
top.labels=c(split_var[1], colnames(data)[1], split_var[2]),
gap=4, ppmar=c(4,2,4,7), do.first="plot_bg(\"#FFFFFF\")")
mtext("Porridge temperature by age and sex of bear", 3, 2, cex=1)
legend("right", inset=c(-0.25,0), legend = colnames(dat_left), fill = cols)
})32 32
p
