How to Change Legend Size in Base R Plot (With Examples)


The easiest way to change the size of a legend in a base R plot is to use the cex argument:

legend('topright', legend=c('A', 'B'), col=1:2, pch=16, cex=1)

The default value for cex is 1.

The larger the value that you specify for cex, the larger the legend will be.

The following example shows how to use this argument in practice.

Example: Change Legend Size in Base R Plot

Suppose we create the following scatter plot in base R:

#create data frame
df <- data.frame(x=c(1, 2, 3, 4, 5, 6),
                 y=c(4, 6, 7, 12, 6, 8),
                 group=c(1, 1, 1, 2, 2, 2))

#create scatter plot
plot(df$x, df$y, col=df$group, pch=16)

#add legend in top right corner
legend('topright', legend=c('First', 'Second'),
       col=1:2, pch=16)

To increase the legend size, we can increase the value for cex to some value greater than 1:

#create scatter plot
plot(df$x, df$y, col=df$group, pch=16)

#add legend in top right corner with increased size
legend('topright', legend=c('First', 'Second'),
       col=1:2, pch=16, cex=2)

increase legend size in base R plot

Notice how much larger the legend is in this plot compared to the previous plot.

To decrease the legend size, we can decrease the value for cex to some value less than 1:

#create scatter plot
plot(df$x, df$y, col=df$group, pch=16)

#add legend in top right corner with decreased size
legend('topright', legend=c('First', 'Second'),
       col=1:2, pch=16, cex=.75)

decrease legend size in base R plot

Also note that you can change the point size in a legend by changing the value for the pt.cex argument.

The default value for this argument is 1, but you can increase the point size in the legend by increasing this value:

#create scatter plot
plot(df$x, df$y, col=df$group, pch=16)

#add legend in top right corner with increased point size
legend('topright', legend=c('First', 'Second'),
       col=1:2, pch=16, pt.cex=2)

Notice that the legend size is the same, but the red and black points in the legend are twice as large.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Draw a Legend Outside of a Plot in R
How to Change Legend Position in Base R Plots

Leave a Reply

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