# How to Fix in R: plot.new has not been called yet

One error you may encounter when using R is:

```Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
```

This error occurs when you attempt to perform some action that requires a plot to already exist in R, yet a plot does not exist.

The following examples show how to fix this error in practice.

### Example 1: How to Fix Error with lines()

Suppose we attempt to plot a fitted regression line in 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```

We receive an error because we can’t use the lines() function without first creating a plot in R.

To fix this error, we can first create a scatterplot and then use the lines() function:

```#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))) ``` Notice that we don’t receive an error because we first used the plot() function before using the lines() function.

### Example 2: How to Fix Error with abline()

Suppose we attempt to create a scatterplot with a straight horizontal line in 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
```

We receive an error because we can’t use the abline() function without first creating a plot in R.

To fix this error, we can first create a scatterplot and then use the abline() function:

```#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) 