Pregunta

I am trying to overlay two graphs onto the same axes. I set up my axes limits and labels first, but then when I plot the graphs they resize and are not on my pre-determined scale.

I have pared my code down into a simple example. You can see that 100 and 10 are showing up at the same place on the y axis. Please help!

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)
¿Fue útil?

Solución

You want to use lines to add the second line, meanwhile making sure that ylim allows for all the values being plotted to fit within the plotting region.

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top