Line graphs with more than one line, representing more than one variable, are quite common in any kind of data analysis. In this recipe, we will learn how to create and customize legends for such graphs.
We will use the base graphics library for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script for use again later.
Once again we will use the cityrain.csv
example dataset that we used in Chapter 1, R Graphics, and Chapter 3, Beyond the Basics – Adjusting Key Parameters:
rain<-read.csv("cityrain.csv") plot(rain$Tokyo,type="b",lwd=2, xaxt="n",ylim=c(0,300),col="black", xlab="Month",ylab="Rainfall (mm)", main="Monthly Rainfall in major cities") axis(1,at=1:length(rain$Month),labels=rain$Month) lines(rain$Berlin,col="red",type="b",lwd=2) lines(rain$NewYork,col="orange",type="b",lwd=2) lines(rain$London,col="purple",type="b",lwd=2) legend("topright...