In this recipe, we will learn how to add and format legends to graphs.
First, we need to load the cityrain.csv
example data file, which contains monthly rainfall data for four major cities across the world (you can download this file from the code download section of the book's companion website):
rain<-read.csv("cityrain.csv",header=TRUE)
In the bar plots recipe, we already saw that we can add a legend by passing the legend argument to the barplot()
function. Now, we see how we can use the legend()
function to add and customize a legend for any type of graph.
Let's first draw a graph with multiple lines representing the rainfall in cities:
plot(rain$Tokyo,type="l",col="red", ylim=c(0,300), main="Monthly Rainfall in major cities", xlab="Month of Year", ylab="Rainfall (mm)", lwd=2) lines(rain$NewYork,type="l",col="blue",lwd=2) lines(rain$London,type="l",col="green",lwd=2) lines(rain$Berlin,type="l",col="orange",lwd=2)
Now, let's add the...