R legend() 函数 - 添加图例
R legend() 函数用于在图形中添加图例,帮助读者识别不同的数据系列。
当图形中包含多组数据时,图例是必不可少的元素。
legend() 函数语法格式如下:
legend(x, y = NULL, legend, col, pch, lty, lwd, fill, title = NULL)
参数说明:
x, y 图例位置:"topright"、"bottomleft" 等关键字,或坐标。
legend 图例文字标签。
col 各数据系列的颜色。
pch 点符号类型。
lty 线型。
实例
# 三类产品的月度销量趋势
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# 绘制折线图
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "各产品月度销量趋势",
xlab = "月份", ylab = "销量")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# 添加图例
legend("topleft",
legend = c("产品A", "产品B", "产品C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "产品类别")
month <- 1:6
product_a <- c(100, 120, 115, 135, 145, 160)
product_b <- c(85, 90, 95, 100, 105, 110)
product_c <- c(60, 70, 80, 75, 90, 88)
# 绘制折线图
plot(month, product_a, type = "o",
col = "steelblue", lwd = 2, pch = 16,
ylim = c(50, 170),
main = "各产品月度销量趋势",
xlab = "月份", ylab = "销量")
lines(month, product_b, type = "o",
col = "coral", lwd = 2, pch = 17)
lines(month, product_c, type = "o",
col = "seagreen", lwd = 2, pch = 18)
# 添加图例
legend("topleft",
legend = c("产品A", "产品B", "产品C"),
col = c("steelblue", "coral", "seagreen"),
pch = c(16, 17, 18),
lwd = 2,
title = "产品类别")
执行以上代码会显示三条销量折线,并带有区分颜色的图例。

R 语言实例