在R中,要在同一图中绘制两个折线图,可以使用基础绘图函数或者ggplot2包来实现。
使用基础绘图函数:
示例代码如下:
# 创建数据集
x1 <- c(1, 2, 3, 4, 5)
y1 <- c(10, 15, 12, 18, 20)
x2 <- c(1, 2, 3, 4, 5)
y2 <- c(5, 8, 6, 10, 12)
# 绘制第一个折线图
plot(x1, y1, type = "l", xlim = c(1, 5), ylim = c(0, 25), xlab = "X", ylab = "Y", main = "Two Line Plots")
lines(x2, y2, col = "red", lty = 2) # 添加第二个折线图
legend("topright", legend = c("Line 1", "Line 2"), col = c("black", "red"), lty = c(1, 2)) # 添加图例
使用ggplot2包:
示例代码如下:
library(ggplot2)
# 创建数据集
data <- data.frame(
x = c(1, 2, 3, 4, 5),
y1 = c(10, 15, 12, 18, 20),
y2 = c(5, 8, 6, 10, 12),
group = c("Line 1", "Line 2")
)
# 创建绘图对象并添加折线图
ggplot(data, aes(x = x, y = y1, color = group)) +
geom_line() +
geom_line(aes(y = y2), linetype = "dashed") +
labs(title = "Two Line Plots", x = "X", y = "Y")
以上代码演示了如何在R中绘制同一图中的两个折线图。对于更复杂的图形需求,可以根据具体情况使用其他绘图函数或包来实现。
领取专属 10元无门槛券
手把手带您无忧上云