在 R 编程中将文本添加到绘图中 - text() 和 mtext()函数
文本被定义为一种描述与图形表示相关的数据的方式。它们可作为任何图形或图形表示的标签。在本文中,我们将学习使用 R 编程语言中的text()和mtext()函数将文本添加到绘图中。
R – text()函数
R 编程语言中的 text ()函数用于在 Base 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
示例 1:
R
# R program to add text to plot
# Calling data set
d<-head(mtcars)
# Plotting the graph
plot(d[, 'wt'], d[, 'mpg'],
main = " Car Weight vs. Milage ",
xlab = "Miles", ylab = " Weight",
pch = 19, col = "darkgreen")
# Calling text() function
text(d[, 'wt'], d[, 'mpg'], row.names(d),
cex = 0.88, pos = 2, col = "darkgreen")
R
# R program to add text to plot
# Plotting the graph
plot(1:5, 1:5,
main = "text() Function examples")
# Calling text() function
text(2, 3, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(3, 4, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
R
# R program to add text to a plot
# Creating a plot
plot(1:5, 1:5,
main = "mtext examples")
# Calling mtext() function
mtext("mtext() function", side = 3)
输出:
在上面的示例中,文本被添加到“mtcar”数据集的图中。
示例 2:实现 text() 以向绘图添加数学注释
R
# R program to add text to plot
# Plotting the graph
plot(1:5, 1:5,
main = "text() Function examples")
# Calling text() function
text(2, 3, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(3, 4, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
输出:
在上面的示例中, text()函数用于向绘图添加数学注释
R - mtext()函数将文本添加到图形的边缘
R 编程语言中的mtext()函数用于将文本添加到绘图的边缘。
Syntax: mtext(text, side)
Parameters:
- text: text to be written
- side: An integer specifying the side of the plot, such as: bottom, left, top, and right.
Returns: Added text in the margins of the graph
例子:
R
# R program to add text to a plot
# Creating a plot
plot(1:5, 1:5,
main = "mtext examples")
# Calling mtext() function
mtext("mtext() function", side = 3)
输出:
在这里,在上面的示例中,side 指定了绘图的一侧,例如底部、左侧、顶部、右侧。并且在给定的 side=3 即图的顶部。