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

Jinku Hu 2023年1月30日 2021年7月14日
  1. 在 R 中使用 legend 函式為繪圖新增圖例
  2. 使用雙 legend 呼叫繪製不同顏色的圖例項
在 R 中繪製不同顏色的圖例項

本文將演示如何在 R 中繪製不同顏色的圖例項。

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

legend 函式用於在圖上繪製圖例物件。它需要 xy 座標作為前兩個引數來指定圖例的位置。雖然可以使用諸如"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) )

r 圖圖例 1

我們還可以通過增加 lty 引數向量的值來新增行。請注意,那些對應於直線和不間斷的線。另一方面,pch 參數列示對映到 0:25 整數值的繪圖符號,並在 points 函式文件中進行了描述。

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)

r 圖圖例 2

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

上一個示例顯示具有相同顏色的單個專案的線條和形狀。這可以通過 legend 函式的兩次呼叫來解決,每個函式都用不同的顏色分別顯示線條和形狀。不過請注意,其中一個呼叫的 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 圖圖例 3

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - R Plot