簡體   English   中英

如何將顏色匹配的圖例添加到 R matplot

[英]How to add colour matched legend to a R matplot

我使用 matplot 在圖表上繪制了幾條線:

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

這為我提供了每行的默認顏色 - 這很好,

但我現在想添加一個反映這些相同顏色的圖例 - 我怎樣才能做到這一點?

請注意 - 我試圖不首先指定 matplot 的顏色。

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

給我所有相同的顏色。

matplot 的默認顏色參數是 data.frame 列的 nbr 上的序列。 所以你可以像這樣添加圖例:

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

在此處輸入圖片說明

我嘗試使用 iris 數據集重現您正在尋找的內容。 我得到了以下表達式的情節:

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

然后,要添加圖例,您可以指定默認線條顏色和類型,即數字 1:4,如下所示:

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

現在您在圖例和情節中都有相同的內容。 請注意,您可能需要相應地更改圖例的坐標。

我喜歡@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")

在此處輸入圖片說明

有趣的是@agstudy 解決方案可以解決問題,但僅適用於 n ≤ 6

這里我們有一個有 8 列的矩陣。 前 6 個標簽的顏色是正確的。 第7個和第8個是錯誤的。 圖中的顏色從頭開始 (black, red ...) ,而在標簽中它繼續 (yellow, grey, ...)

還是沒弄明白為什么會這樣。 我可能會用我的發現更新這篇文章。

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 個以上特征的示例圖像

剛剛發現matplot使用線型 1:5 和顏色 1:6 來建立線條的外觀。 如果要創建圖例,請嘗試以下方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM