Lattice problems: lattice objects coming from JAGS, but device can't be set
I ran JAGS
with runjags
in R
and I开发者_JAVA技巧 got a giant list back (named results for this example).
Whenever I access results$density
, two lattice plots
(one for each parameter) pop up in the default quartz device.
I need to combine these with par(mfrow=c(2, 1))
or with a similar approach, and send them to the pdf device
.
Nothing I tried is working. Any ideas?
I've tried dev.print
, pdf()
with dev.off()
, etc. with no luck.
Here's a way to ditch the "V1" panels by manipulation of the Trellis structure:
p1 <- results$density$c
p2 <- results$density$m
p1$layout <- c(1,1)
p1$index.cond[[1]] <- 1 # remove second index
p1$condlevels[[1]] <- "c" # remove "V1"
class(p1) <- "trellis" # overwrite class "plotindpages"
p2$layout <- c(1,1)
p2$index.cond[[1]] <- 1 # remove second index
p2$condlevels[[1]] <- "m" # remove "V1"
class(p2) <- "trellis" # overwrite class "plotindpages"
library(grid)
layout <- grid.layout(2, 1, heights=unit(c(1, 1), c("null", "null")))
grid.newpage()
pushViewport(viewport(layout=layout))
pushViewport(viewport(layout.pos.row=1))
print(p1, newpage=FALSE)
popViewport()
pushViewport(viewport(layout.pos.row=2))
print(p2, newpage=FALSE)
popViewport()
popViewport()
pot of c.trellis() result http://img142.imageshack.us/img142/3272/ctrellisa.png
The easiest way to combine the plots is to use the results stored in results$mcmc:
# prepare data, see source code of "run.jags"
thinned.mcmc <- combine.mcmc(list(results$mcmc),
collapse.chains=FALSE,
return.samples=1000)
print(densityplot(thinned.mcmc[,c(1,2)], layout=c(1,2),
ylab="Density", xlab="Value"))
For instance, for the included example from run.jags
, check the structure of the list using
sink("results_str.txt")
str(results$density)
sink()
Then you will see components named layout. The layout for the two plots of each variable can be set using
results$density$m$layout <- c(1,2)
print(results$density$m)
The plots for different parameters can be combined using the c.trellis
method from the latticeExtra
package.
class(results$density$m) <- "trellis" # overwrite class "plotindpages"
class(results$density$c) <- "trellis" # overwrite class "plotindpages"
library("latticeExtra")
update(c(results$density$m, results$density$c), layout=c(2,2))
output of c.trellis http://img88.imageshack.us/img88/6481/ctrellis.png
Another approach is to use grid
viewports:
library("grid")
results$density$m$layout <- c(2,1)
results$density$c$layout <- c(2,1)
class(results$density$m) <- "trellis"
class(results$density$c) <- "trellis"
layout <- grid.layout(2, 1, heights=unit(c(1, 1), c("null", "null")))
grid.newpage()
pushViewport(viewport(layout=layout))
pushViewport(viewport(layout.pos.row=1))
print(results$density$m, newpage=FALSE)
popViewport()
pushViewport(viewport(layout.pos.row=2))
print(results$density$c, newpage=FALSE)
popViewport()
popViewport()
grid output http://img88.imageshack.us/img88/5967/grida.png
精彩评论