O'Reilly logo

R: Data Analysis and Visualization by Ágnes Vidovics-Dancs, Kata Váradi, Tamás Vadász, Ágnes Tuza, Balázs Árpád Szucs, Julia Molnár, Péter Medvegyev, Balázs Márkus, István Margitai, Péter Juhász, Dániel Havran, Gergely Gabler, Barbara Dömötör, Gergely Daróczi, Ádám Banai, Milán Badics, Ferenc Illés, Edina Berlinger, Bater Makhabel, Hrishi V. Mittal, Jaynal Abedin, Brett Lantz, Tony Fischetti

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding and formatting legends

In this recipe, we will learn how to add and format legends to graphs.

Getting ready

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)

How to do it...

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), ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required