How To Make A Legend In R [Good Clean Graphs in R]

So you are wondering how to make a legend in r. After all, a graph can be meaningless to the viewer without an indication as to what the data plot is referring to. A legend box is a good way of informing those who view your graph about what each line indicates.

Description of the function

The r legend function has the format of legend(x, y, legend, col, lty, cex, title, box, bg) and adds a legend box to a plotting area. It works with a barplot, and pie chart as well as a data point graph.

  • x and y – Location on the graph of the legend box
  • legend – The legend text.
  • col – Colors of lines and points
  • lty – Number of line segments per line
  • cex – Langth of the lines
  • title – Title of legend
  • box – Describe the outline
  • bg – Background color

Explanation of the Function

This function simply produces a box within the graph of multiple plots that defines the elements of the graph. It helps the user of the graph to understand the elements of the graph.

Examples of the Function in Action

Here are three examples of this function being used. It is used with the same graph for Simplicity.

> x=0:10; y1=x^2; y2=4*x
> plot(x, y1, type=”b”, pch=19, col=”red”, xlab=”x”, ylab=”y”)
> lines(x, y2, pch=18, col=”blue”, type=”b”)
> legend(0, 85, legend=c(“y=x^2”, “y=4*x”),
+ col=c(“red”, “blue”), lty=1:1, cex=1)

This example produces a simple box with red and blue lines next to the appropriate labels indicating the function used.

x=0:10; y1=x^2; y2=4*x
> plot(x, y1, type=”b”, pch=19, col=”red”, xlab=”x”, ylab=”y”)
> lines(x, y2, pch=18, col=”blue”, type=”b”)
> legend(0, 85, legend=c(“y=x^2”, “y=4*x”),
+ col=c(“red”, “blue”), lty=1:1, cex=1,
+ title=”Functions”, bg=’yellow’)

This example produces a box with a title above the red and blue lines next to the appropriate labels indicating the function used. It also has a yellow background.

x=0:10; y1=x^2; y2=4*x
> plot(x, y1, type=”b”, pch=19, col=”red”, xlab=”x”, ylab=”y”)
> lines(x, y2, pch=18, col=”blue”, type=”b”)
> legend(0, 85, legend=c(“y=x^2”, “y=4*x”),
+ col=c(“red”, “blue”), lty=1:1, cex=1,
+ title=”Functions”, box.lty=0)

This example produces a box with a title above the red and blue lines next to the appropriate labels indicating the function used. In this case, there is no outline.

These are just three of the possible ways this function can be used. The best way to fully understand this function is to play around with it to see the different configurations you can come up with.

This add legend function for r programming is pretty simple, but it has many options that can make it more complex. This is a function need to play around with to find the exact configuration you need. It is a useful and important function to use with graphs but it is also one that is fun to work with.

Scroll to top
Privacy Policy