Custom graphical device in Sweave

不打扰是莪最后的温柔 提交于 2019-12-04 04:10:02

问题


My problem of inserting a pdf graphic with a special character in a Sweave document has been solved by creating the pdf plot outside Sweave itself and then importing it.

Following the Sweave documentation, I have written a custom graphical device which should construct the pdf graphic exactly in the same way. However it doesn't work. Can you explain me why the second graphic of the Sweave document below does not work whereas it should be created exactly as the first one ? Am I wrong to believe it should ?

\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

<<setup, echo=FALSE>>=
mycairo <- function(name, width = 7, height = 7, ...) { 
  grDevices::cairo_pdf(name, width = width, height = height)
}
mycairo.off <- function() {
    cat("shutting down mycairo\n")
    invisible(grDevices::dev.off())
}
@

\section{Export plot}

<<Export_plot, echo=FALSE>>=
cairo_pdf("exported_plot.pdf")
par(mar=c(6,7,0,6))
ylab <- expression(paste("", bar(italic("\u2113")), "(",phi[0], "|", italic(list(x,y)), ")"))
plot(0,0, ylab=ylab, xlab=NA, cex.lab=3)
invisible(dev.off())
@

% insert exported plot 
\includegraphics[width=6cm]{exported_plot.pdf}


\section{Direct plot}

<<mycairo_plot, echo=FALSE,  fig=TRUE, pdf=TRUE, grdevice=mycairo, width=4, height=4>>=
par(mar=c(6,6,0,6))
ylab <- expression(paste("", bar(italic("\u2113")), "(",phi[0], "|", italic(list(x,y)), ")"))
plot(0,0, ylab=ylab, xlab=NA, cex.lab=1)
@


\end{document}


回答1:


@user20650 kindly proposed me to convert the answer given in his/her comment to an official one.

It suffices to include the pdf file extension in the cairo_pdf function. Then replace the mycairo function with:

mycairo <- function(name, width = 7, height = 7, ...) { 
  grDevices::cairo_pdf(sprintf("%s.pdf", name), width = width, height = height)
}

As a side note, instead of specifying grdevice=mycairo in each figure chunk, you can also set it as a global option:

\SweaveOpts{grdevice=mycairo}


来源:https://stackoverflow.com/questions/31221471/custom-graphical-device-in-sweave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!