# Change Legend Position in Base R Plots

There are two ways to change the legend position in base R plots:

Method 1: Use (x, y) coordinates

```legend(4, 12, legend=c('y1', 'y2'), col=c('purple', 'red'), lty=1)
```

Method 2: Use keywords

```legend('bottomright', legend=c('y1', 'y2'), col=c('purple', 'red'), lty=1)
```

Using this method, you can specify the following locations:

• “bottomright”
• “bottom”
• “bottomleft”
• “left”
• “topleft”
• “top”
• “topright”
• “right”
• “center”

The following examples show how to use each method in practice.

### Example 1: Change Legend Position Using (x, y) Coordinates

The following code shows how to create a legend for a plot in base R and place it at x=4 and y=12:

```#create data
x <- 1:10
y1<- c(3, 6, 8, 7, 8, 9, 13, 12, 10, 10)
y2 <- c(1, 3, 3, 4, 6, 7, 8, 10, 9, 9)

#create plot with multiple lines
plot(x, y1, col='purple', type='l', xlab='x', ylab='y')
lines(x, y2, col='red')

legend(4, 12, legend=c('y1', 'y2'), col=c('purple', 'red'), lty=1)```

Notice that the legend is placed at the exact (x,y) coordinates that we specified.

### Example 2: Change Legend Position Using Keywords

The following code shows how to create a legend for a plot in base R and place it in the top left corner:

```#create data
x <- 1:10
y1<- c(3, 6, 8, 7, 8, 9, 13, 12, 10, 10)
y2 <- c(1, 3, 3, 4, 6, 7, 8, 10, 9, 9)

#create plot with multiple lines
plot(x, y1, col='purple', type='l', xlab='x', ylab='y')
lines(x, y2, col='red')

legend('topleft', legend=c('y1', 'y2'), col=c('purple', 'red'), lty=1)```

We can easily change it to a different location, such as the bottom right corner, by using a different keyword:

```#create data
x <- 1:10
y1<- c(3, 6, 8, 7, 8, 9, 13, 12, 10, 10)
y2 <- c(1, 3, 3, 4, 6, 7, 8, 10, 9, 9)

#create plot with multiple lines
plot(x, y1, col='purple', type='l', xlab='x', ylab='y')
lines(x, y2, col='red')