# 在 R 中繪製不同顏色的圖例項

Lasha Khintibidze 2023年1月30日 2021年7月14日 R R Plot

## 在 R 中使用 `legend` 函式為繪圖新增圖例

`legend` 函式用於在圖上繪製圖例物件。它需要 `x``y` 座標作為前兩個引數來指定圖例的位置。雖然可以使用諸如`"left"``"bottomright"`等關鍵字來指定它。下一個引數稱為 `legend`，它表示為需要在圖例中顯示的字元向量。在這種情況下，我們繪製由三角形或圓形表示的線和點。線和點有不同的顏色，它們需要相應地顯示在圖例中。以下程式碼片段僅在圖例中繪製形狀和文字。

``````library(ggplot2)

plot( 0, type = "n", xlim = c(0,5), ylim = c(0,5) )
A <- matrix( c( c(4,1,3,2), c(1,3,4,4)), ncol = 2 )
B <- matrix( c( c(1,4,3,2), c(1,3,1,1)), ncol = 2 )

lines( A, col = "brown" )
points( A, col = "blue", pch = 17 )
lines( B, col = "cyan" )
points( B, col = "purple", pch = 19 )

legend( x = "topleft",
legend = c("Brown line, blue triangles","Cyan line, purple points"),
col = c("blue","purple"), lwd = 2, lty = c(0,0),
pch = c(17,19) )
``````

``````library(ggplot2)

plot( 0, type = "n", xlim = c(0,5), ylim = c(0,5) )
A <- matrix( c( c(4,1,3,2), c(1,3,4,4)), ncol = 2 )
B <- matrix( c( c(1,4,3,2), c(1,3,1,1)), ncol = 2 )

lines( A, col = "brown" )
points( A, col = "blue", pch = 17 )
lines( B, col = "cyan" )
points( B, col = "purple", pch = 19 )

legend( x = "topleft",
legend = c("Brown line, blue triangles","Cyan line, purple points"),
col = c("brown","cyan"), lwd = 1, lty = c(1,1),
pch = c(17,19), merge = FALSE)
``````

## 使用雙 `legend` 呼叫繪製不同顏色的圖例項

``````library(ggplot2)

plot( 0, type = "n", xlim = c(0,5), ylim = c(0,5) )
A <- matrix( c( c(4,1,3,2), c(1,3,4,4)), ncol = 2 )
B <- matrix( c( c(1,4,3,2), c(1,3,1,1)), ncol = 2 )

lines( A, col = "brown" )
points( A, col = "blue", pch = 17 )
lines( B, col = "cyan" )
points( B, col = "purple", pch = 19 )

legend( x = "topleft",
legend = c("Brown line, blue triangles","Cyan line, purple points"),
col = c("brown","cyan"), lwd = 1, lty = c(1,1),
pch = c(NA,NA) )

legend( x = "topleft",
legend = c("",""),
col = c("blue","purple"), lwd = 1, lty = c(0,0),
pch = c(17,19), bty= 'n')
``````

## 相關文章 - R Plot

• R 中的 scale_fill_continuous
• 從(x,y,z) 座標建立 3D 曲面圖
• R 中的正態概率圖
• 在 R 中建立 3D 透檢視
• Base R 中的色盲無障礙顏色
• 在 R 中自定義 PCA Biplot