Draw Legend Outside of Plot Area in Base R Graphic (Example Code)

 

On this page you’ll learn how to draw a legend outside of the plotting area of a Base R graphic in the R programming language.

Table of contents:

You’re here for the answer, so let’s get straight to the example.

 

Introducing Example Data

Let’s first create some data that we can plot later on:

set.seed(123)                                             # Set seed
data <- data.frame(x = c(rnorm(100), rnorm(100, 2)),      # Create example data
                   y = c(rnorm(100), rnorm(100, 2)),
                   group = c(rep(1, 100), rep(2, 100)))

As you can see, our example data contains an x-column, a y-column, as well as a grouping variable. Now let’s create a graph illustrating this data!

 

Example: Draw Legend Outside of Plotting Area

Here comes the trick: We have to specify the xpd argument within the par function to be TRUE. Furthermore, we leave some additional space around the plot with the mar argument:

par(mar = c(5, 4, 4, 8),                                  # Specify par parameters
    xpd = TRUE)

Now, we can display our plot in Base R as usual:

plot(data$x, data$y,                                      # Create plot
     pch = data$group,
     col = data$group)

In order to draw our legend outside of the plotting area, we can use a combination of the “topright” argument and an additional specification of inset.

The “topright” argument specifies that the legend should be in the upper right corner of the graph. The inset argument allows to change the position of the legend (i.e. a bit more to the right).

Let’s have a look at the R code and the output:

legend("topright", inset = c(- 0.4, 0),                   # Create legend outside of plot
       legend = c("Group 1","Group 2"),
       pch = 1:2,
       col = 1:2)

 

plot with legend outside base r

Figure 1: Base R Plot with Legend Outside of Plotting Area.

 

Figure 1 illustrates the output of the previous R syntax. A plot with a legend outside the plotting region.

 

Video, Further Resources & Summary

Some time ago I have published a video on the Statistics Globe YouTube channel, which explains the R syntax of this article. You can find the video below.

 

 

In addition, you may have a look at the other RStudio tutorials on this homepage.

 

At this point you should have learned how to visualize a legend outside of an R plot in R programming. Please let me know in the comments, in case you have further questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top