How to add legend to a Plot with R software?
Hey there! Hope you are doing great. In this new post, I will show you how to add a legend to a plot with R software.
To do this we will use function legend().
Let first describe how this function work and show some examples.
How do Legend() function work ?
The function legend() is slightly complex and I will try to simplify the presentation. Here is how the function is presented.
x and y are the coordinates to be used to position the legend.
legend : is the character or the the name you use to specify each of the legends in your plot.
fill = is the box filled with the color related to the chart on the figure.
border = is the border color of the boxes representing the color of the graphs. Also it is used only "fill" is used.
lty = the line types and widths for lines appearing in the legend. It must be specified for line drawing.
lwd = the line widths for lines appearing in the legend. It must be specified for line drawing.
pch = the plotting symbols appearing in the legend, as numeric vector or a vector of 1-character strings.
angle = angle of shading lines.
ncol = is the number of columns in which to set the legend items (default is 1, a vertical legend).
title = a character string presenting the title to be placed at the top of the figure.
title.col = the color of the title.
title.adj = horizontal adjustment for title.
Just to precise here that I have only presented a few and essential functionalities used for this legend().
Example of using legend() function with R
I have simulated the data for this example. Here is the code for the simulations. Indeed, the code create the seed number, then we simulate 2 variables following a random normal distribution. Therefore we create 3 groups randomly selected on the whole sample.
Here is the plot of the data putting in relationship the variable Z and the Y for the 3 different groups.
Now, let's add the legend on the graph. We will first add the legend at the top right of the figure. That is my preferred location where I put legends. Here is the code.
Here is the graph obtained.
As the box of the legend is hidding some of the dot on the graph. We can change it to the topright. Then we can change in the function legend "topright" by "topleft". Then, here is the code.
And here is the result of the graph.
You can also change "topleft" to "bottomleft" in order to put the box of legends at the bottom left of the figure or "bottomright" in order to put the box of legends at the bottom right. Here is the example with bottom left.
Here is the figure.
The last advice I should give is that you should always place the legends in such a way that the plot is not hidden.
That's all for this post. I hope this post would be helpful. If you liked the post, please share it with friends and your community of machine learning engineers and data science. See you on the next post.