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

2019-02-22 15:21:01 浏览数 (1)

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

示例

代码语言:javascript复制
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

0 人点赞