R语言之可视化(20)之geom_label()和geom_text()

目录

R语言之可视化①误差棒

R语言之可视化②点图

R语言之可视化③点图续

R语言之可视化④点韦恩图upsetR

R语言之可视化⑤R图形系统

R语言之可视化⑥R图形系统续

R语言之可视化⑦easyGgplot2散点图

R语言之可视化⑧easyGgplot2散点图续

R语言之可视化⑨火山图

R语言之可视化⑩坐标系统

R语言之可视化①①热图绘制heatmap

R语言之可视化①②热图绘制2

R语言之可视化①③散点图+拟合曲线

R语言之可视化①④一页多图(1)

R语言之可视化①⑤ROC曲线

R语言之可视化①⑥一页多图(2)

R语言之可视化①⑦调色板

R语言之可视化①⑧子图组合patchwork包

R语言之可视化①⑨之ggplot2中的图例修改

R语言之可视化(20)之geom_label()和geom_text()

Geom_text()将文本直接添加到绘图中。 geom_label()在文本后面绘制一个矩形,使其更易于阅读。

示例

p <- [ggplot](mtcars, aes(wt, mpg, label = rownames(mtcars)))
p + geom_text()
image

避免字体重叠

p + geom_text(check_overlap = TRUE)

image

给label加上背景

p + geom_label()

image

修改字体大小

p + geom_text(size = 10)

image

p + geom_point() + geom_text(hjust = 0, nudge_x = 0.05)

image

p + geom_point() + geom_text(vjust = 0, nudge_y = 0.5)

image

p + geom_point() + geom_text(angle = 45)

image

添加映射

p + geom_text(aes(colour = factor(cyl)))

image

p + geom_text(aes(colour = factor(cyl))) +
scale_colour_discrete(l = 40)

image

p + geom_label(aes(fill = factor(cyl)), colour = "white", fontface = "bold")

image

p + geom_text(aes(size = wt))

image

缩放文本高度

p + geom_text(aes(size = wt)) + scale_radius(range = c(3,6))

image

可以通过设置parse = TRUE来显示表达式。themama中描述了显示的详细信息,但请注意geom_text使用字符串,而不是表达式。

p + geom_text(aes(label = paste(wt, "^(", cyl, ")", sep = "")),
parse = TRUE)

image

添加一个注释

p +geom_text() +annotate("text", label = "plot mpg vs. wt", x = 2, y = 15, size = 8, colour = "red")

image

对齐标签和条形

df <- data.frame(
x = factor(c(1, 1, 2, 2)),
y = c(1, 3, 2, 1),
grp = c("a", "b", "a", "b")
)

ggplot2不知道你想给标签赋予相同的虚拟宽度

ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp), position = "dodge") +
geom_text(aes(label = y), position = "dodge")

image

ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp), position = "dodge") +
geom_text(aes(label = y), position = position_dodge(0.9))

image

#使用你无法轻推和躲避文字,所以改为调整y位置

ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp), position = "dodge") +
geom_text(
aes(label = y, y = y + 0.05),
position = position_dodge(0.9),
vjust = 0
)

image

如果将文本放在堆积的条形图中每个条形图的中间,需要设置position_stack()的vjust参数

ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp)) +
geom_text(aes(label = y), position = position_stack(vjust = 0.5))

image

推荐阅读更多精彩内容