Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R and knitr, how do I plot INLA results?

I'm trying to inlude some INLA code in my knitr document and print plots:

Using a trivial example

\documentclass{article}

\begin{document}

<<c1>>=
library("INLA")

n = 100
z = runif(n)
eta = 1 + 0.1*z
N = 20

p = exp(eta)/(1+exp(eta))
y = rbinom(n,  size = N, prob = p)
r = inla(y ~ 1 + z,  
         data = data.frame(y, z), 
         family = "binomial", 
         Ntrials = rep(N, n),
        control.family = list(link = "logit"), 
        control.predictor = list(compute=TRUE)
        )
@

<<c2>>=
plot(r, single=TRUE)
@

\end{document}

When I run this code interactively inside RStudio all works fine and I get a series of plots. However after kniting document - none of them gets included.

How can I fix that?

UPDATE 1 I posted the question asking for clarification from the package package developer on Google groups.

UPDATE 2 Havard Rue from INLA developers group posted a Sweave solution on Google Groups. The trick is:

<<results=tex, echo=FALSE>>=
figs = plot(r, single=TRUE, postscript=TRUE, prefix="Sweave/ex1/figure-")

cat("\\begin{figure}[tbp]\n")
cat("\n")
cat("\\centering\n")

for(i in 1:length(figs)) {
    cat("\\includegraphics[width=7cm,height=7cm,angle=-90]{",
    gsub("[.]eps$","",figs[i]), "}\n", sep="")
}

cat("\\caption{XXX}\n")
cat("\\label{fig:11}\n")
cat("\\end{figure}\n")
@

That does seem to do the job. Graphs are created in specified directory and then placed inside the pdf output. Some tinkering is necessary however for placing and sizing since the knitr controls doesn't seem to work any longer.

like image 871
radek Avatar asked Jan 12 '23 07:01

radek


1 Answers

INLA seems to be doing some non-standard things when plotting. If not running in RStudio, it opens up a new plotting window (device) when it plots. I think that means that knitr is not seeing the plots because they are not on the device that knitr is using/monitoring.

Perhaps you can trick INLA by adding a chunk

<<>>=
op <- options(device="RStudioGD")
@

at the start of your knitr file and

<<>>=
options(op)
@

at the end of the file (to reset the default device to something appropriate).

This is untested because I don't have INLA installed.

It may require modifying INLA (specifically inla.dev.new) to not open a new device. One approach that might work is

noop <- function(...) NULL
assignInNamespace("inla.dev.new", noop, ns="INLA")

This, also, is untested and could potentially break other parts of INLA.

like image 90
Brian Diggs Avatar answered Jan 18 '23 14:01

Brian Diggs