你在使用R时可能遇到的一个错误是。
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
当你试图执行一些需要在R中已经存在一个情节的操作时,却发现一个情节并不存在,就会出现这个错误。
下面的例子展示了如何在实践中修复这个错误。
例1:如何修复lines()的错误
假设我们试图在R中绘制一条拟合的回归线。
#create data
df <- data.frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))
#fit polynomial regression model
model <- lm(y~poly(x, 2), data=df)
#define new sequence of x-values
new_x <- seq(min(df$x), max(df$y))
#attempt to plot fitted regression line
lines(new_x, predict(model, newdata = data.frame(x=new_x)))
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
我们收到了一个错误,因为我们不能在没有在R中创建一个图的情况下使用lines()函数。
为了解决这个错误,我们可以先创建一个散点图,然后再使用lines()函数。
#create data
df <- data.frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))
#fit polynomial regression model
model <- lm(y~poly(x, 2), data=df)
#define new sequence of x-values
new_x <- seq(min(df$x), max(df$y))
#create scatterplot of x vs. y values
plot(y~x, data=df)
#attempt to plot fitted regression line
lines(new_x, predict(model, newdata = data.frame(x=new_x)))
注意,我们没有收到错误,因为我们在使用lines( **)函数之前首先使用了plot()**函数。
例2:如何用abline()修复错误
假设我们试图在R中创建一个带有水平直线的散点图。
#create data
df <- data.frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))
#attempt to add horizontal line at y=10
abline(a=10, b=0, lwd=2)
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
我们收到了一个错误,因为我们不能在没有在R中创建一个图的情况下使用abline()函数。
为了解决这个错误,我们可以先创建一个散点图,然后再使用abline()函数。
#create data
df <- data.frame(x=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28))
#create scatterplot of x vs. y
plot(y~x, data=df)
#add horizontal line at y=10
abline(a=10, b=0, lwd=2)
注意,我们没有收到错误,因为我们在使用abline( )函数之前首先使用了plot()函数。
其他资源
下面的教程解释了如何修复R中的其他常见错误:
如何在R中修复。意外的字符串常数
如何在R中修复:ExtractVars中无效的模型公式
如何在R中修复:参数不是数字或逻辑:返回na