Change Legend Position in R Plots with examples

Change Legend Position in R

In base R plots, there are two ways to adjust the legend position.

Method 1: Use (x, y) coordinates

`legend(5, 10, 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)`

You can provide the following places using this method

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

The examples below demonstrate how to apply each strategy in practice.

Example 1: Change the position of the legend Using Coordinates (x, y)

The following code demonstrates how to place a legend for a plot at x=5 and y=10 in basic R.

Let’s create the data set first,

```x <- 1:10
y1<- c(5, 8, 8, 10, 8, 7, 12, 11, 8, 7)
y2 <- c(2, 1, 4, 5, 8, 9, 8, 9, 8, 9)```

Now we can create a plot with multiple lines

```plot(x, y1, col='green', type='l', xlab='x', ylab='y')
lines(x, y2, col='red')```

Let’s add a legend to the plot

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

The legend is positioned at the precise (x,y) coordinates that we requested.

Example 2: Using Keywords to Change Legend Position

The code below demonstrates how to make a legend for a plot in R and insert it in the upper left corner.

```x <- 1:10
y1<- c(5, 8, 8, 10, 8, 7, 12, 11, 8, 7)
y2 <- c(2, 1, 4, 5, 8, 9, 8, 9, 8, 9)```

Now, we can create a 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)`

The legend is at the top left corner of the plot, exactly where we said it should be.

By utilizing a different keyword, we may simply move it to a new area, such as the bottom right corner.

```x <- 1:10
y1<- c(5, 8, 8, 10, 8, 7, 12, 11, 8, 7)
y2 <- c(2, 1, 4, 5, 8, 9, 8, 9, 8, 9)```

Let’s create a plot with multiple lines

`plot(x, y1, col='purple', type='l', xlab='x', ylab='y')`

lines(x, y2, col=’red’)

Now we can add the bottom right legend

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

The legend has been moved to the plot’s bottom right corner.

Decision tree regression and Classification » finnstats