R语言 向ggplot2绘图添加文本
在这篇文章中,我们将看到如何在R编程语言中向ggplot2图添加文本。
为了做到这一点,我们使用了 annotate() 。它对于添加小的注释(如文本标签)或如果你的数据是向量的,但由于某些原因不想把它们放在数据框中,是很有用的。
语法
annotate(geom,x = NULL,y = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, xend = NULL, yend = NULL, ..., na.rm = FALSE)
参数
- geom:用于注释的几何体名称
- x, y, xmin, ymin, xmax, ymax, xend, yend: 定位美学 – 你必须至少指定其中之一。
- …:传递给layer()的其他参数。这些通常是美学,用于将美学设置为一个固定的值,如color = “red” 或size = 3。
- na.rm。如果是FALSE,默认情况下,缺失的值会被删除并发出警告。
例子
library("ggplot2")
gfg_data <- data.frame(x = c(1,2,3,4,5),
y = c(4,3,2,5,1))
gfg_data
gfg_plot<- ggplot(gfg_data, aes(x, y)) +
geom_point()
gfg_plot + annotate("text", x = 4, y = 3,
label = "GeeksForGeeks")
输出
要在ggplot2图上标注多个测试元素,用户需要在R编程语言中多次调用ggplot2包的annotate()函数,并输入所需参数。
例子
library("ggplot2")
gfg_data <- data.frame(x = c(1,2,3,4,5),
y = c(4,3,2,5,1))
gfg_data
gfg_plot<- ggplot(gfg_data, aes(x, y)) +
geom_point()
gfg_plot + annotate("text", x = 1.2, y = 5,
label = "GeeksForGeeks") +
annotate("text", x = 4.7, y = 1,
label = "GeeksForGeeks")
输出
要使用annotate()函数修改添加到ggplot2图中的文本的颜色和大小,用户需要从ggplot2包中添加 col 和 size 作为annotate函数的参数,并在该函数中指定所需参数,这将导致在R编程语言中添加到ggplot2图中的文本的大小和颜色发生变化。
例子
library("ggplot2")
gfg_data <- data.frame(x = c(1,2,3,4,5),
y = c(4,3,2,5,1))
gfg_data
gfg_plot<- ggplot(gfg_data, aes(x, y)) +
geom_point()
gfg_plot + annotate("text", x = 2, y = 5,
label = "GeeksForGeeks",
col = "green", size = 10) +
annotate("text", x = 4.7, y = 1,
label = "GeeksForGeeks",
col = "green", size = 5)
输出