有没有一种方法可以绘制2个y值和一个x

时间:2019-04-27 17:16:55

标签: r

我想绘制一个具有两个y值的图,但是我似乎找不到任何使它起作用的方法,我想让代码看起来像这样:

x1 = c(1,2,3,4,5)
y1 = c(10,13,15,17,11)
y2 = c(5,7,8,3,5)

plot(x1, y1, y2)

但是我得到了错误:

Error in plot.xy(xy, type, ...) : invalid plot type

3 个答案:

答案 0 :(得分:1)

您也可以使用ggplot

library(ggplot)
ggplot() + 
  geom_point(aes(x = x1, y = y1)) + 
  geom_point(aes(x = x1, y = y2))

enter image description here

答案 1 :(得分:1)

使用matplot作为 @jogo 的建议

matplot(x1, cbind(y1, y2), pch=c(1, 2), col=c(2, 3), xlab="x", ylab="y", main="My plot")
legend("topleft", legend=c("y1", "y2"), pch=c(1, 2), col=c(2, 3))

enter image description here

答案 2 :(得分:0)

为完整起见,基本R解决方案如下所示:

> x1 = c(1,2,3,4,5)
> y1 = c(10,13,15,17,11)
> y2 = c(5,7,8,3,5)
> plot(x1, y1, type='l', ylim=c(0,20))
> lines(x1, y2, type='l', col='red')