如何将颜色匹配的图例添加到 R matplot [英] How to add colour matched legend to a R matplot

查看:57
本文介绍了如何将颜色匹配的图例添加到 R matplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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?

请注意 - 我一开始不想为 matplot 指定颜色.

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

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

给我所有相同的颜色.

推荐答案

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

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

cars数据集为例,这里是添加图例的完整代码.最好使用 layout 以漂亮的方式添加图例.

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

这篇关于如何将颜色匹配的图例添加到 R matplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆