R语言如何修复:plot.new has not been called yet
在这篇文章中,我们将讨论如何在R编程语言中修复 “plot.new还没有被调用 “的错误。
当我们试图进行一个需要在R中存在一个情节的操作,但该情节还不存在时,R编译器会产生这样的错误。
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
方法1:如何用lines()函数修复
这里我们将重点讨论如何修复R编译器在处理lines()函数时可能产生的错误。
例子
让我们考虑一个例子,我们有两个向量,分别存放着12个不同点的相应X和Y坐标。然后我们用lines()函数来画连接这些点的线。
# R program to add lines into plots
# Constructing coordinate vectors
x <- c(1.7, 2.7, 3.7, -3.7, -5.7,
3.7, 5.7, 4.8, 10.3, -12.9, 13.8, 12.3)
y <- c(1.2, 2.3, 3.2, -3.5, -3.2, 2.1,
4.7, .8, 1.2, 11.5, 1.3, 3.2)
# Trying to draw lines of red colors
lines(x, y, col = "red")
输出
R编译器产生这样的错误是因为我们在使用lines()函数之前没有创建绘图。我们可以通过在使用lines()函数之前创建一个图来轻松解决这个错误。
例子
在这里,在这个例子中,我们通过在lines()函数之前简单地调用plot函数来修复上述错误,以获得给定的点的概念。
# R program to add lines into plots
# Constructing coordinate vectors
x <- c(1.7, 2.7, 3.7, -3.7, -5.7,
3.7, 5.7, 4.8, 10.3, -12.9, 13.8, 12.3)
y <- c(1.2, 2.3, 3.2, -3.5, -3.2, 2.1,
4.7, .8, 1.2, 11.5, 1.3, 3.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3,
xlab ="x", ylab ="y",
col ="black")
# Trying to draw lines of red colors
lines(x, y, col = "red")
输出
这次程序编译成功了,因为我们在使用lines()函数之前已经创建了绘图。
方法2:如何用abline()函数修复
在这一部分中,我们重点讨论如何修复R编译器在处理abline()函数时可能产生的错误。
例子
让我们考虑一个例子,我们有两个向量,分别存放着12个不同点的相应X和Y坐标。然后我们用ablines()函数在Y=5处画一条水平线。
# R program to add a horizontal line
# Constructing coordinate vectors
x <- c(1.7, 2.7, 3.7, -3.7, -5.7,
3.7, 5.7, 4.8, 10.3, -12.9, 13.8, 12.3)
y <- c(1.2, 2.3, 3.2, -3.5, -3.2, 2.1,
4.7, .8, 1.2, 11.5, 1.3, 3.2)
# Try to add horizontal line at y=5
abline(a=5, b=0, lwd=3)
输出
R编译器产生这样的错误是因为我们在使用abline()函数之前没有创建绘图。我们可以通过在使用abline()函数之前创建一个图来轻松解决这个错误。
例子
因此,在这里为了解决上述错误,我们在使用abline函数之前调用plot()函数,并给定参数,通过这样做,程序编译成功,没有任何错误。
# R program to add a horizontal line
# Constructing coordinate vectors
x <- c(1.7, 2.7, 3.7, -3.7, -5.7,
3.7, 5.7, 4.8, 10.3, -12.9, 13.8, 12.3)
y <- c(1.2, 2.3, 3.2, -3.5, -3.2, 2.1,
4.7, .8, 1.2, 11.5, 1.3, 3.2)
# Plotting the graph
plot(x, y, cex = 1, pch = 3,
xlab ="x", ylab ="y",
col ="black")
#attempt to add horizontal line at y=5
abline(a=5, b=0, lwd=3)
输出