How to add a color legend to the matte matrix R

I draw several lines on a graph using matplot:

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

This gives me the default colors for each line - this is normal,

But now I want to add a legend that reflects the same colors - how can I achieve this?

PLEASE NOTE - I try not to specify colors for matplot in the first place.

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

Gives me the same color.

+4
source share
3 answers

The default color option for matplot is the sequence over the nbr column of your data.frame. So you can add this legend:

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

cars , . layout, .

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

+3

@agstudy, .

, @agstudy ggplot2:

  • - ""

    require(reshape2)
    df <- data.frame(x=1:nrow(cars), cumsum(data.frame(cars)))
    df.melted <- melt(df, id="x")
    
  • matplot

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

enter image description here

+2

I tried to reproduce what you are looking for using the iris kit. I get a graph with the following expression:

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

Then, to add a legend, you can specify the default color and type of lines, i.e. the numbers 1: 4 as shown below:

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

Now you have the same thing in the legend and in the plot. Please note that you may need to change the coordinates for the legend.

+1
source

Source: https://habr.com/ru/post/1570136/


All Articles