Custom Graphics Device in Sweave

My problem with inserting a PDF graphic with a special character in a Sweave document was solved by creating a PDF graphic outside of Sweave itself and importing it later.

Following the Sweave documentation, I wrote my own graphics device, which should accurately build pdf graphics. However, this will not work. Can you explain to me why the second drawing of the Sweave document below does not work, whereas it should be created exactly the same as the first? Am I mistaken to believe this?

\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} 

enter image description here

+4
r pdf utf-8 sweave graphics
source share
1 answer

@ user20650 kindly invited me to convert the answer given in his comment to the official one.

It is enough to include the pdf extension in the cairo_pdf function. Then replace 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 image fragment, you can also set it as a global option:

 \SweaveOpts{grdevice=mycairo} 
+3
source share

All Articles