Reputation: 1137
I am trying to make one figure by stacking two graphs (a) and (b) vertically (i.e., a multiple plot with 2 rows, 1 column).
While I can do this for other plots I have tried, the following two plots generated from data using the ODE solver package deSolve refuse to be combined. On the screen, plot (a) flashes by and I am left looking at plot (b). Saving the plots results in 1 pdf file with 2 pages (each plot on a separate page) rather than 1 pdf file and 1 page (with both plots stacked into one figure as I am seeking).
As you can see from the code I have tried both mfrow and layout approaches to no avail. Any help would be greatly appreciated.
Thanks, Carey
df1 <-function(t,y,mu)( list(c(y[2], mu*y[1]^3 - y[1] + 0.005 * cos(t))))
library(deSolve)
yini <- c(y1=0, y2=0)
df2 <-ode(y = yini, func = df1, times = 0:1050, parms = 0.1667)
t <- seq(0, 1050, length=10000)
x <- 0.24 * (1 - cos(0.012 * t)) * cos(t + sin(0.012 * t))
pdf("c:/users/name/Desktop/figure2.pdf", height = 3, width=8)
# par(mfrow = c(2, 1))
layout(matrix(c(1, 2), 2, 1, byrow = TRUE))
plot(df2, type="l", which="y1", ylab="x", xlab="t", main="(a)")
plot(t, x, type="l", main="(b)")
dev.off()
Upvotes: 1
Views: 540
Reputation: 29477
The problem is that deSolve
objects have their own plot method, and that overrides what happens with layout. As soon as your first plot is run, the layout set up is completely undone and the display is configured in terms of the defaults for deSolve
objects. That's why there's a flash when the second plot writes over the first since there is no longer a multi-panel display.
The plot method is ?plot.deSolve - this function takes mfrow/mfcol arguments, so you can work with your layout as intended.
layout(matrix(c(1, 1, 2, 2), 2, 2, byrow = TRUE))
plot(df2, type="l", which = "y1", ylab = "x", xlab = "t", main = "(a)", mfrow = c(2, 1))
plot(t, x, type = "l", main = "(b)")
Upvotes: 3