如何将颜色匹配的图例添加到 R matplot

Man*_*oon 7 plot r

我使用 matplot 在图表上绘制了几条线:

matplot(cumsum(as.data.frame(daily.pnl)),type="l")
Run Code Online (Sandbox Code Playgroud)

这为我提供了每行的默认颜色 - 这很好,

但我现在想添加一个反映这些相同颜色的图例 - 我怎样才能做到这一点?

请注意 - 我试图不首先指定 matplot 的颜色。

legend(0,0,legend=spot.names,lty=1)
Run Code Online (Sandbox Code Playgroud)

给我所有相同的颜色。

ags*_*udy 5

matplot 的默认颜色参数是 data.frame 列的 nbr 上的序列。所以你可以像这样添加图例:

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

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明