How to Draw a Legend Outside of a Plot in R?
In this article, we will discuss how to draw a legend outside of a Plot in the R Programming Language.
We first create a basic plot without legend using the plot() function and add a margin around it for legend by using the par() function of the R Language. We will create the required margin and make the xpd parameter TRUE. This will make our plotting clipped to the figure region.
par( mar, xpd)
- mar: determines the vector which contains margin.
- xpd: It is a boolean. If FALSE, all plotting is clipped to the plot region, if TRUE, all plotting is clipped to the figure region
Then we use the legend() function to add a legend layer on top of it. To put the legend at the desired position on the plot we use the inset parameter of the legend function.
legend(position, inset, title, legend, pch, col )
- position: determines the position of the legend.
- inset: determines the shift in position.
- title: determines the title of legend.
- pch: determines the symbols used to represent the data point.
- col: determines the color of data points.
Here, is a basic plot in the R Language with the legend on the top right corner of the plot.
Here, is a basic plot in the R Language with the legend on the bottom of the plot.