# 安装包
if (!requireNamespace("data.table", quietly = TRUE)) {
install.packages("data.table")
}
if (!requireNamespace("jsonlite", quietly = TRUE)) {
install.packages("jsonlite")
}
if (!requireNamespace("CGPfunctions", quietly = TRUE)) {
install.packages("CGPfunctions")
}
if (!requireNamespace("ggplot2", quietly = TRUE)) {
install.packages("ggplot2")
}
# 加载包
library(data.table)
library(jsonlite)
library(CGPfunctions)
library(ggplot2)斜面图
注记
Hiplot 网站
本页面为 Hiplot Slopegraph 插件的源码版本教程,您也可以使用 Hiplot 网站实现无代码绘图,更多信息请查看以下链接:
斜面图可以用于展示数值变化情况。
环境配置
系统: Cross-platform (Linux/MacOS/Windows)
编程语言: R
依赖包:
data.table;jsonlite;CGPfunctions;ggplot2
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-28
pandoc 3.1.3 @ /usr/bin/ (via rmarkdown)
quarto 1.8.27 @ /usr/local/bin/quarto
─ Packages ───────────────────────────────────────────────────────────────────
package * version date (UTC) lib source
CGPfunctions * 0.6.3 2025-11-17 [1] Github (ibecav/CGPfunctions@999a2c1)
data.table * 1.18.0 2025-12-24 [1] RSPM
ggplot2 * 4.0.1 2025-11-14 [1] RSPM
jsonlite * 2.0.0 2025-03-27 [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/slopegraph/data.json")$exampleData$textarea[[1]])
data <- as.data.frame(data)
# 整理数据格式
data[, "country"] <- factor(data[ ,"country"], levels = unique(data[ ,"country"]))
data[, "year"] <- factor(data[ ,"year"], levels = unique(data[ ,"year"]))
# 查看数据
head(data) country continent year lifeExp pop gdpPercap
1 Costa Rica Americas 1992 76 3173216 6160.416
2 Costa Rica Americas 1997 77 3518107 6677.045
3 Costa Rica Americas 2002 78 3834934 7723.447
4 Costa Rica Americas 2007 79 4133884 9645.061
5 El Salvador Americas 1992 67 5274649 4444.232
6 El Salvador Americas 1997 70 5783439 5154.825
可视化
# 斜面图
p <- newggslopegraph(data, year, lifeExp, country) +
labs(subtitle = "", title = "Slope Graph", x = "Life Expectancy (years)",
y = "country", caption = "") +
scale_color_manual(values = c("#3B4992FF", "#EE0000FF", "#008B45FF",
"#631879FF", "#008280FF", "#BB0021FF")) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5))
p
