使用ggplot2添加文本标签

使用ggplot2添加文本标签

这里演示如何使用geom_text()将文本添加为​​标记。它的工作原理与geom_point()几乎相同,但添加的是文本而不是圆圈。

  • label: 你想显示什么文本
  • nudge_xnudge_y: 沿 X 和 Y 轴移动文本
  • check_overlap尽量避免文本重叠。请注意,一个名为的包ggrepel进一步扩展了这个概念

代码如下:

#图1 基本图
library(ggplot2)
 
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
 
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_text(
    label=rownames(data), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )
使用ggplot2添加文本标签插图
图1

geom_label()工作方式与geom_text(). 但是,文本被包裹在一个可以自定义的矩形中(参见下一个示例)。

# 图2
library(ggplot2)
 
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
 
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_label(
    label=rownames(data), 
    nudge_x = 0.25, nudge_y = 0.25, 
    check_overlap = T
  )
使用ggplot2添加文本标签插图1
图2

仅添加一个文本标签时:

#图3
library(ggplot2)
 
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
 
# Add one annotation
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_label(
    label="Look at this!", 
    x=4.1,
    y=20,
    label.padding = unit(0.55, "lines"), # Rectangle size around label
    label.size = 0.35,
    color = "black",
    fill="#69b3a2"
  )
使用ggplot2添加文本标签插图2
图3

为选择的标记添加标签:

# 图4
library(ggplot2)
library(dplyr)
library(tibble)

# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)

# Change data rownames as a real column called 'carName'
data <- data %>%
  rownames_to_column(var="carName")
  
# Plot
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + 
  geom_label( 
    data=data %>% filter(mpg>20 & wt>3), # Filter data first
    aes(label=carName)
  )
使用ggplot2添加文本标签插图3
图4

摘自:https://r-graph-gallery.com/275-add-text-labels-with-ggplot2.html