# 在 R 中绘制不同颜色的图例项

Jinku Hu 2024年2月15日

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

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

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景，但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。