簡體   English   中英

線型(或標記)和基本 R 圖中顏色的圖例

[英]Legend for line type (or marker) and for colour in base R plot

我有一個圖表,其中有幾種顏色和幾種線型。 並且它們是交叉的,例如虛線是藍色或綠色。 我想要一個在 R 中使用基本繪圖的圖例,該圖例將位於正方形/矩形中,其中行是顏色,列是線型。

更新:

在@G 的回答的幫助下。 Grothendieck,我已經了解如何獲得兩列,但標簽仍然沒有按照我想要的方式排列。 使用this answer將標簽放置在左側,我想出了如何讓標簽出現在符號的左側(盡管我覺得到達那里很費力,而且應該更簡單)。 我已經使用了那個答案的存根和我在這里找到的那​​個來創建這個例子。

set.seed(1)
plot(1:10,runif(min=0,max=10,10),type='l',ylim=c(0,15),xlim=c(0,10),col=1)
lines(1:10,runif(min=0,max=10,10),col=1,lty="dashed")
lines(1:10,runif(min=0,max=10,10),col=2,lty="solid")
lines(1:10,runif(min=0,max=10,10),col=2,lty="dashed")
lines(1:10,runif(min=0,max=10,10),col=3,lty="solid")
lines(1:10,runif(min=0,max=10,10),col=3,lty="dashed")
#draw the legend lines
a <- legend(1,14,lty=rep(ltys, each = (nr)),col=1:3,legend=rep("",6),bty="n", ncol=nc,
        trace=TRUE)
#place text labels one value to the left of the legend lines for only the first column
text(a$text$x[1:3]-1,a$text$y[1:3],Vars,pos=2)
#place a text label above the legend lines for the second attribute to define in legend
text(a$text$x[c(1,4)]-1.5, 14, c("Young", "Old"), pos=4)

在此處輸入圖片說明

有沒有更簡單的東西,或者這是 R 可以給我的最好的東西?

1)這里第一行是黑色,第二行是紅色,第三行是綠色。 第一列是實線,第二列是虛線。 我們使用 title= 來提供列的標題。 這將需要一些反復試驗才能正確定位。 請參閱 (2) 以獲取替代方案。

nc <- 2   
Vars <- c("VarA", "VarB", "VarC")
nr <- length(Vars)

plot(0)
legend("topleft", rep(Vars, nc), col = 1:nr, 
   lty = rep(1:nc, each = nr), ncol = nc, cex = 0.8, 
   title = "        Young              Old")

截屏

2)這是類似的,但我們添加了一行沒有行作為標題,避免了title方法的繁瑣反復試驗。

nc <- 2   
Vars <- c("VarA", "VarB", "VarC")
nr <- length(Vars)

plot(0)
legend("topleft", c("Young", Vars, "Old", Vars), col = 0:nr, 
   lty = 0:nr, ncol = nc, cex = 0.8)

暫無
暫無

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

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