在 R 中绘制带有标签的散点图
在本文中,我们将研究在 R 编程语言中绘制带有标签的散点图的不同方法。
方法一:使用 text()函数
在这种使用 text()函数绘制带有标签的散点图的方法中,用户需要调用 text()函数,该函数用于在 R 编程语言中使用所需的参数在图中添加标签。
Syntax: text(x, y, labels)
Parameters:
x and y: numeric values specifying the coordinates of the text to plot
labels: the text to be written
Returns: Added text to plot
例子:
R
gfg_data <- data.frame(x =c(1,2,3,4,5),
y = c(5,4,3,2,1),
lab=c('g','e','e','k','s'))
gfg_data
plot(gfg_data$x,
gfg_data$y)
text(gfg_data$x,
gfg_data$y,
labels = gfg_data$lab,
pos = 4)
R
gfg_data <- data.frame(x =c(1,2,3,4,5),
y = c(5,4,3,2,1),
lab=c('g','e','e','k','s'))
gfg_data
ggplot(gfg_data, aes(x, y, label = lab)) + geom_point() +
geom_text(aes(label = lab), hjust = - 0.5)
输出:
方法 2 :使用 geom_text()函数
在这种绘制带有标签的散点图的方法中,用户首先需要安装并加载 ggplot2 包,并使用所需的参数从 ggplot2 包中调用 geom_text()函数,这将导致绘制带有标签的散点图。
Syntax: geom_text(mapping = NULL, data = NULL, stat = “identity”,position = “identity”, parse = FALSE, …)
Parameters:
- parse:-If TRUE, the labels will be parsed into expressions and displayed as described in ?plotmath.
- mapping:-The aesthetic mapping, usually constructed with aes or aes_string.
- data:-A layer-specific dataset – only needed if you want to override the plot defaults.
- stat:-The statistical transformation to use on the data for this layer.
- position:-The position adjustment to use for overlapping points on this layer
- …:-other arguments passed on to layer. This can include aesthetics whose values you want to set, not map.
例子:
电阻
gfg_data <- data.frame(x =c(1,2,3,4,5),
y = c(5,4,3,2,1),
lab=c('g','e','e','k','s'))
gfg_data
ggplot(gfg_data, aes(x, y, label = lab)) + geom_point() +
geom_text(aes(label = lab), hjust = - 0.5)
输出: