至少有四种方法可以做到这一点:
(1) 此处使用名为 df 的“水平”或“宽”data.frame
df <- data.frame(x = c(0, 5, 10, 15), y = c(2.2, 3.8, 4.6, 7.6),z = c(4.5, 6.8, 9.3, 10.5))
ggplot(df, aes(x)) +
geom_line(aes(y = y, colour = "y")) +
geom_line(aes(y = z, colour = "z"))
(2) 使用格子
library(lattice)
xyplot(x ~ y + z, data=df, type = c('l','l'), col = c("blue", "red"), auto.key=T)
(3) 将原始 df 变成“长”data.frame。这就是您通常处理数据的方式ggplot2
library(reshape)
library(ggplot2)
mdf <- melt(df, id="x") # convert to long format
ggplot(mdf, aes(x=x, y=value, colour=variable)) +
geom_line() +
theme_bw()
(4) 使用 matplot() 我还没有真正探索过这个选项,但这里有一个例子。
matplot(df$x, df[,2:3], type = "b", pch=19 ,col = 1:2)