如何在 R 中的 ggplot2 中直接添加标签
标签是文本实体,具有有关它们所附加的数据点的信息,有助于确定这些数据点的上下文。在本文中,我们将讨论如何在 R 编程语言中直接为 ggplot2 添加标签。
为了将标签直接放在 ggplot2 图中,我们在数据框中添加了与标签相关的数据。然后我们使用函数 geom_text() 或 geom_label() 在每个数据点旁边创建标签。这两个功能的工作原理相同,唯一的区别是外观。 geom_label() 比 geom_text() 更具可定制性。
方法一:使用 geom_text()
此方法用于向 ggplot2 图中的数据点添加文本标签。它以与 geom_point() 相同的方式定位。
Syntax: ggp + geom_text( label, nudge_x , nudge_y, check_overlap )
Parameters:
- label: Text labels we want to show at data points
- nudge_x: shifts the text along X-axis
- nudge_y: shifts the text along Y-axis
- check_overlap: avoids text overlap
示例:使用 ggplot2 和 geom_text 带有标签的散点图。
R
# import library ggplot2
library(ggplot2)
# Create dataset
x1 < - c(1, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 2, 3)
y1 < - c(7, 23, 31, 14, 11, 3, 13, 27, 21, 10, 21, 14, 30)
label1 < - c('Apple', 'Guava', 'Papaya', 'Orange', 'PineApple',
'Dragon Fruit', 'Kiwi', 'blackberry', 'blueberry',
'grapes', 'strawberry', 'raspberry', 'Grapefruit')
sample_data < - data.frame(x1, y1, label1)
# add text with geom_text
ggplot(sample_data, aes(x=x1, y=y1)) +
geom_point() +
geom_text(
label=label1,
nudge_x=0.45, nudge_y=0.1,
check_overlap=T
)
R
# import library ggplot2
library(ggplot2)
# Create dataset
x1 < - c(1, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 2, 3)
y1 < - c(7, 23, 31, 14, 11, 3, 13, 27, 21, 10, 21, 14, 30)
label1 < - c('Apple', 'Guava', 'Papaya', 'Orange', 'PineApple',
'Dragon Fruit', 'Kiwi', 'blackberry', 'blueberry',
'grapes', 'strawberry', 'raspberry', 'Grapefruit')
sample_data < - data.frame(x1, y1, label1)
# add text with geom_text
ggplot(sample_data, aes(x=x1, y=y1)) +
geom_point() +
geom_label(
label=label1,
nudge_x=0.45, nudge_y=0.1,
check_overlap=T,
label.padding=unit(0.55, "lines"),
label.size=0.4,
color="white",
fill="#038225"
)
输出:
方法二:使用geom_label()
此方法用于向 ggplot2 图中的数据点添加文本标签。它的工作原理与 geom_text 几乎相同,唯一的区别是它将标签包裹在一个矩形内。
Syntax: ggp + geom_label( label, nudge_x , nudge_y, check_overlap, label.padding, label.size, color, fill )
Parameters:
- label: Text labels we want to show at data points
- nudge_x: shifts the text along X-axis
- nudge_y: shifts the text along Y-axis
- check_overlap: avoids text overlap
- label.padding: padding inside rectangular overlap
- label.size: size of rectangular overlap
- color: color of text in label
- fill: background color of rectangular overlap
示例:使用 ggplot2 和 geom_label() 带有标签的散点图。
电阻
# import library ggplot2
library(ggplot2)
# Create dataset
x1 < - c(1, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 2, 3)
y1 < - c(7, 23, 31, 14, 11, 3, 13, 27, 21, 10, 21, 14, 30)
label1 < - c('Apple', 'Guava', 'Papaya', 'Orange', 'PineApple',
'Dragon Fruit', 'Kiwi', 'blackberry', 'blueberry',
'grapes', 'strawberry', 'raspberry', 'Grapefruit')
sample_data < - data.frame(x1, y1, label1)
# add text with geom_text
ggplot(sample_data, aes(x=x1, y=y1)) +
geom_point() +
geom_label(
label=label1,
nudge_x=0.45, nudge_y=0.1,
check_overlap=T,
label.padding=unit(0.55, "lines"),
label.size=0.4,
color="white",
fill="#038225"
)
输出: