简体   繁体   中英

How to add colour matched legend to a R matplot

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.

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

在此处输入图片说明

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, ie, 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")

在此处输入图片说明

Interestingly @agstudy solution does the trick, but only for n ≤ 6

Here we have a matrix with 8 columns. The colour of the first 6 labels are correct. The 7th and 8th are wrong. The colour in the plots restarts from the beginning (black, red ...) , whereas in the label it continues (yellow, grey, ...)

Still haven't figured out why this is the case. I'll maybe update this post with my findings.

matplot(x = lambda, y = t(ridge$coef), type = "l", main="Ridge regression", xlab="λ", ylab="Coefficient-value", log = "x")
nr = nrow(ridge$coef)
legend("topright", rownames(ridge$coef), col=seq_len(nr), cex=0.8, lty=seq_len(nr), lwd=2)

具有 6 个以上特征的示例图像

Just discovered that matplot uses linetypes 1:5 and colors 1:6 to establish the appearance of the lines. If you want to create a legend try the following approach:

## Plot multiple columns of the data frame 'GW' with matplot
cstart = 10           # from column 
cend = cstart + 20    # to column 
nr <- cstart:cend
ltyp <- rep(1:5, times=length(nr)/5, each=1) # the line types matplot uses
cols <- rep(1:6, times=length(nr)/6, each=1) # the cols matplot uses 

matplot(x,GW[,nr],type='l')
legend("bottomright", as.character(nr), col=cols, cex=0.8, lty=ltyp, ncol=3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM