R中使用不同轴的重叠图

时间:2014-03-20 01:42:09

标签: r plot overlay axis axes

我试图将两个图形叠加到相同的轴上。我首先设置我的轴​​限制和标签,但是当我绘制图表时,他们调整大小并且不是我预先确定的尺度。

我把我的代码简化为一个简单的例子。您可以看到100和10显示在y轴上的相同位置。请帮忙!

x<- 1:3
y1<- c(100, 75, 20)
y2<- c(10, 9, 4)

plot.new()                              
plot(0, type="n",    
     xlim=c(1,max(x)), ylim=c(0,max(y1,y2)),
     xlab= "x label", ylab= "y label", main= "This stupid graph doesn't work!")
par(new=TRUE)
par(new=TRUE)
plot(x,y1, type="b", pch=19, col="orchid", 
     axes=FALSE, ann=FALSE)
par(new=TRUE)
plot(x,y2, type="b", pch=19, col="slateblue", 
     axes=FALSE, ann=FALSE)
legend("topright",c("This is","Annoying"), col=c("orchid","slateblue"), pch=19)

1 个答案:

答案 0 :(得分:1)

您希望使用lines添加第二行,同时确保ylim允许绘制的所有值都适合绘图区域。

plot(y1 ~ x, ylim = range(c(y1, y2)), xlab = "x label", ylab = "y label",
       main = "This one might work!", type = 'b', pch = 19, col = "orchid")
lines(y2, type = 'b', pch = 19, col = 'slateblue')
legend("topright", c("R is", "awesome"), col = c("orchid","slateblue"), pch = 19)

enter image description here