How to add colour matched legend to a R matplot

The default color parameter to matplot is a sequence over the nbr of column of your data.frame. So you can add legend like this :

nn <- ncol(daily.pnl)
legend("top", colnames(daily.pnl),col=seq_len(nn),cex=0.8,fill=seq_len(nn))

Using cars data set as example, here the complete code to add a legend. Better to use layout to add the legend in a pretty manner.

daily.pnl <- cars
nn <- ncol(daily.pnl)
layout(matrix(c(1,2),nrow=1), width=c(4,1)) 
par(mar=c(5,4,4,0)) #No margin on the right side
matplot(cumsum(as.data.frame(daily.pnl)),type="l")
par(mar=c(5,0,4,2)) #No margin on the left side
plot(c(0,1),type="n", axes=F, xlab="", ylab="")
legend("center", colnames(daily.pnl),col=seq_len(nn),cex=0.8,fill=seq_len(nn))

enter image description here


I have tried to reproduce what you are looking for using the iris dataset. I get the plot with the following expression:

matplot(cumsum(iris[,1:4]), type = "l")

Then, to add a legend, you can specify the default lines colour and type, i.e., numbers 1:4 as follows:

legend(0, 800, legend = colnames(iris)[1:4], col = 1:4, lty = 1:4)

Now you have the same in the legend and in the plot. Note that you might need to change the coordinates for the legend accordingly.


I like the @agstudy's trick to have a nice legend.

For the sake of comparison, I took @agstudy's example and plotted it with ggplot2:

  • The first step is to "melt" the data-set

    require(reshape2)
    df <- data.frame(x=1:nrow(cars), cumsum(data.frame(cars)))
    df.melted <- melt(df, id="x")
    
  • The second step looks rather simple in comparison to the solution with matplot

    require(ggplot2)
    qplot(x=x, y=value, color=variable, data=df.melted, geom="line")
    

enter image description here

Tags:

Plot

R