如何在ggplot2图中添加文本(附实例)

2,442 阅读2分钟

你可以使用annotate()函数来为ggplot2中的图添加文本。

这个函数使用以下基本语法:

p +
  annotate("text", x=6, y=10, label= "hello")

where:

  • x, y:应放置文本的(x,y)坐标。
  • label:要显示的文本。

下面的例子展示了如何在实践中使用这个函数。

例1:向ggplot2添加一个文本元素

下面的代码展示了如何使用**annotate()**在ggplot2的散点图中添加一个文本元素:

library(ggplot2)

#create data frame
df <- data.frame(x=c(1, 3, 3, 5, 7, 8, 10, 11),
                 y=c(3, 5, 7, 5, 8, 10, 14, 19))

#create scatter plot with one text element
ggplot(df, aes(x=x, y=y)) +
  geom_point()
  annotate("text", x=6, y=10, label= "hello")

注意,我们的文本元素已经被添加到图中的(x,y)坐标(6,10)。

例2:向ggplot2添加多个文本元素

下面的代码显示了如何使用annotate()在ggplot2的散点图中添加多个文本元素:

library(ggplot2)

#create data frame
df <- data.frame(x=c(1, 3, 3, 5, 7, 8, 10, 11),
                 y=c(3, 5, 7, 5, 8, 10, 14, 19))

#create scatter plot with one text element
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  annotate("text", x=6, y=10, label= "hello") +
  annotate("text", x=3, y=15, label= "hello again")

请注意,在我们指定的坐标处,有两个文本元素被添加到图中。

例3:自定义图中的文本元素

我们可以使用大小颜色斜体粗体参数来分别定制绘图中文本元素的大小、颜色和字体风格:

library(ggplot2)

#create data frame
df <- data.frame(x=c(1, 3, 3, 5, 7, 8, 10, 11),
                 y=c(3, 5, 7, 5, 8, 10, 14, 19))

#create scatter plot with custom text element
ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  annotate("text", x=6, y=10, label= "bolditalic(hello)",
           col="blue", size=10, parse=TRUE)

请注意,图中的一个文本元素现在是粗体、斜体、蓝色,大小为10。

:你可以在这里找到ggplot2中annotate()函数的完整文档。

其他资源

下面的教程解释了如何在R中执行其他常见任务:

如何在ggplot2中改变点的大小
如何在ggplot2中改变标题位置
如何在ggplot2中删除轴的标签