0%

ggplot2集锦之七文本注释函数

在基础绘图系统中,注释功能主要由次级函数来实现,如text()函数可以添加文本、mtext()函数添加轴标签、segments()添加短线、arrows()函数添加箭头、rect()函数添加矩形等。而在ggplot2绘图系统中,一方面可以使用一些几何图形函数、统计变换函数充当注释函数,另一方面它还有专门的注释函数annotate()。
本文总结一下ggplot2包中的文本注释函数,包括:geom_text()、geom_label()、annotate()。

1. geom_text()

geom_text()的用法和ggplot2中图形函数的使用规则一致:

1
2
3
4
5
6
7
8
9
10
11
12
13
geom_text(
mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
...,
parse = FALSE,
nudge_x = 0,
nudge_y = 0,
check_overlap = FALSE,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE)

参数:

  • nudge_x、nudge_y:偏移量;与vjust和hjust参数不同的是,它的单位和对应坐标轴的刻度相同;
  • check_overlap:逻辑型参数;若设为TRUE,则重叠的文本注释会被去除。
1
2
3
4
5
library(ggplot2)

p <- ggplot(mtcars, aes(x = wt, y = mpg, col = vs)) +
geom_point()
p

添加标签:

1
p + geom_text(aes(label = rownames(mtcars), vjust = 1, hjust = "outward"))

alt 图标

利用check_overlap把重复的文本去掉:

1
2
p + geom_text(aes(label = rownames(mtcars), vjust = 1, hjust = "outward"),
check_overlap = T)

alt 图标

给条形图添加注释:

1
2
3
ggplot(mtcars[c(1:10),],aes(x = rownames(mtcars[c(1:10),]),y = mpg))+
geom_bar(stat="identity")+
geom_text(aes(label=mpg,y = mpg+1))

alt 图标

2. geom_label()

geom_label()函数用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
geom_label(
mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
...,
parse = FALSE,
nudge_x = 0,
nudge_y = 0,
label.padding = unit(0.25, "lines"),
label.r = unit(0.15, "lines"),
label.size = 0.25,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE)

参数:

  • label.padding:标签文本与外框的距离大小;
  • label.r:外框圆角的半径;
  • label.size:外框线条的尺寸,单位为毫米(mm)。
1
2
3
4
p + geom_label(aes(label = rownames(mtcars)), nudge_x = 0.15,
label.padding = unit(0.1, "lines"),
label.r = unit(0.05, "lines"),
label.size = 0.1)

alt 图标
可以看到标签有大量的重叠,可以用ggrepel包注释避免重叠。

3. geom_label_repel()与geom_text_repel()

1
2
3
4
library(ggrepel)

p+geom_text_repel(aes(wt,mpg,label=rownames(mtcars)))
p+geom_label_repel(aes(wt,mpg,label=rownames(mtcars)))

alt 图标

参数:

  • segment.color:连接点与标签的线段的颜色
  • segment.size:线段的粗细
  • segment.alpha:线段的透明度
  • box.padding:文本框周边填充
  • point.padding:点周围填充
  • arrow:grid:arrow提供的箭头
  • force:强制性将重叠文本散开
  • max.oter:最大迭代次数
  • nudge_x/y:标签开始位置在坐标轴的移动距离
  • direction:允许标签的方向,x、y or both

4. annotate()

1
2
3
4
5
p1 <- p + annotate("text", x = c(2, 5), y = c(15, 25),
label = c("text1", "text2"))
p2 <- p + annotate("label", x = c(2, 5), y = c(15, 25),
label = c("label1", "label2"))
p1+p2

alt 图标