Add Legend to a plot with Legend Function in R

Legend function in R adds legend box to the plot. legend() function in R makes graph easier to read and interpret in better way. lets see an example on how to add legend to a plot with legend() function in R.

Syntax of Legend function in R:

legend(x, y = NULL, legend, fill = NULL, col = par(“col”),border = “black”, lty, lwd, pch)

 

x, y the x and y co-ordinates which is used to position the legend.
legend a character vector of legend names
fill fill legend box with the specified colors.
col the color of points or lines appearing in the legend.
border the border color for the legend box
lty, lwd the line types and widths for lines appearing in the legend.
pch the plotting symbols appearing in the legend

 

Example of Legend function in R:

Let’s depict how to create legend in R with an example.

#plot a scatter plot

x1 <- c(3,3,4,-3,-2,5,2)
y1 <- c(2,4,2,2,-3,3,7)
plot(x1,y1,cex=.8,pch=1,xlab="x axis",ylab="y axis",col="red")

output will be

legend function in r 1

 

#plot an another scatter plot with points function

x2 <- c(1,2,-2,-1,-2,3)
y2 <- c(2,3,2,2,-2,3)
points(x2,y2,cex=.8,pch=2,col="blue")

So the resultant chart will be

legend function in r 2

 

Add legend to the top left corner of the plot with legend function in R:

Now let’s add the legend to the above scatter plot with legend function in R, to make it more readable

## adding legend to the top left of the plot

legend(x=-3,y=7,c("sample1","sample2"),cex=.8,col=c("red","blue"),pch=c(1,2))

In the above function we have added legend to the top left corner of the graph at co-ordinates x= -3 and y=7 so the output will be

legend function in r at top left 3

 

Add legend to the top right corner of the plot with legend function in R:

## adding legend to the top right corner of the plot

legend(x=4,y=7,c("sample1","sample2"),cex=.8,col=c("red","blue"),pch=c(1,2))

In the above function we have added legend to the top right corner of the graph at co-ordinates x= 4 and y=7 so the output will be

legend function in r at top right 4

previous small legend function in R                                                                                                                next small legend function in r