在ggplot2图中添加曲形文字注释
在现有的ggplot2
绘图系统中,使用geom_text
和geom_label
在已有的图层上添加文字、标签,是大多数图的理想选择。
通常情况下,geom_text
和geom_label
适用于文本长度较短,并且与轴的方向保持一致的注释。
但是,在某些情况下,使文本遵循弯曲的路径很有用,它可以展现出更加自然的视觉效果。
基于ggplot2
绘图系统的geomtextpath
包可以实现以上功能。
geomtextpath
整合了绘图函数与文本标签,将文本附着在其关联的图形元素上,既能保持与图形元素相同的曲线形状,又无需指定确切的标签位置,具有较低的超标风险。
# 安装geomtextpath
# install.packages("remotes")
remotes::install_github("AllanCameron/geomtextpath")
1
2
2
# 使用geomtextpath
# geom_textline
and geom_labelline
ggplot(pressure, aes(temperature, pressure)) +
geom_textline(label = "Mercury vapor pressure", size = 6, vjust = -0.5,
linewidth = 1, linecolor = "red4", linetype = 2,
color = "deepskyblue4")
1
2
3
4
2
3
4
# geom_textdensity
and geom_labeldensity
ggplot(iris, aes(x = Sepal.Length, colour = Species, label = Species)) +
geom_textdensity(size = 6, fontface = 2, hjust = 0.2, vjust = 0.3) +
theme(legend.position = "none")
1
2
3
2
3
# Reference Line
ggplot(mtcars, aes(mpg, disp)) +
geom_point() +
geom_texthline(yintercept = 200, label = "displacement threshold",
hjust = 0.8, color = "red4") +
geom_textvline(xintercept = 20, label = "consumption threshold", hjust = 0.8,
linetype = 2, vjust = 1.3, color = "blue4") +
geom_textabline(slope = 15, intercept = -100, label = "partition line",
color = "green4", hjust = 0.6, vjust = -0.2)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# geom_textpath
与极坐标系很好的融合
p <- data.frame(x1 = c(seq(0, 10/6 * pi, pi/3),
seq(0, 10/6 * pi, 2*pi/3)),
y1 = c(rep(2, 6), rep(-1, 3)),
x2 = c(seq(0, 10/6 * pi, pi/3) + pi/3,
seq(0, 10/6 * pi, 2*pi/3) + 2*pi/3),
y2 = c(rep(4, 6), rep(2, 3)),
group = letters[c(1:6, (1:3) * 2)],
alpha = c(rep(1, 6), rep(0.4, 3))) |>
ggplot(aes(x1, y1)) +
geom_rect(aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2, fill = group,
alpha = alpha),
color = "white", size = 2) +
geom_textpath(data = data.frame(x1 = seq(0, 2 * pi, length = 300),
y1 = rep(0.5, 300),
label = rep(c("stats", "effects", "polar"), each = 100)),
aes(label = label), linetype = 0, size = 8,
upright = TRUE) +
geom_textpath(data = data.frame(x1 = seq(0, 2 * pi, length = 300),
y1 = rep(3, 300),
label = rep(c("density", "smooth", "unique", "organic",
"easy to use", "automatic"),
each = 50)),
aes(label = label), linetype = 0, size = 4.6, color = "white",
upright = TRUE) +
scale_y_continuous(limits = c(-5, 4)) +
scale_x_continuous(limits = c(0, 2*pi)) +
scale_fill_manual(values = c("deepskyblue3", "deepskyblue4",
"green3", "green4","tomato", "tomato2")) +
scale_alpha_identity() +
theme_void() +
theme(legend.position = "none")
p
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
p + coord_polar()
1
编辑 (opens new window)
上次更新: 2022/03/23, 10:03:34