Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add colour matched legend to a R matplot

Tags:

plot

r

I plot several lines on a graph using matplot:

matplot(cumsum(as.data.frame(daily.pnl)),type="l")

This gives me default colours for each line - which is fine,

But I now want to add a legend that reflects those same colours - how can I achieve that?

PLEASE NOTE - I am trying NOT to specify the colours to matplot in the first place.

legend(0,0,legend=spot.names,lty=1)

Gives me all the same colour.

like image 215
ManInMoon Avatar asked Jan 06 '15 10:01

ManInMoon


2 Answers

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

like image 175
agstudy Avatar answered Sep 27 '22 21:09

agstudy


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.

like image 36
ELCano Avatar answered Sep 27 '22 20:09

ELCano