在R中的多线图上添加图例的方法有多种。以下是其中两种常用的方法:
方法一:使用图例函数legend()
示例代码:
# 创建一个空白的图形窗口
plot(1, type = "n", xlim = c(0, 10), ylim = c(0, 20), xlab = "X", ylab = "Y")
# 绘制多条线
lines_plot <- plot(c(1, 2, 3, 4), c(5, 10, 15, 20), type = "l", col = "red")
lines_plot <- plot(c(1, 2, 3, 4), c(8, 12, 14, 18), type = "l", col = "blue")
# 添加图例
legend(x = 1, y = 10, legend = c("Line 1", "Line 2"), col = c("red", "blue"), lty = c(1, 2), lwd = c(2, 2), bty = "n")
方法二:使用ggplot2包
示例代码:
library(ggplot2)
# 创建一个数据框
data <- data.frame(x = c(1, 2, 3, 4), y1 = c(5, 10, 15, 20), y2 = c(8, 12, 14, 18))
# 创建绘图图层并绘制多条线
ggplot(data) +
geom_line(aes(x = x, y = y1, color = "Line 1")) +
geom_line(aes(x = x, y = y2, color = "Line 2")) +
labs(x = "X", y = "Y") +
scale_color_manual(values = c("red", "blue"), guide = guide_legend(title = NULL))
这样,你就可以在R中的多线图上成功添加图例了。
领取专属 10元无门槛券
手把手带您无忧上云