have knitr output figures in different formats - r

Let's say I have a long report that produces a lot of figures which knitr makes as pdfs and it works really well with LaTeX. At the end of the project, my co-authors would like to have also raster based figures. One option would be to convert everything using ImageMagick. Another option would be to specify for each chunk dev = c("jpg", "pdf"), but given the number of figures, this could be cumbersome.
Is there a global switch to make knitr produce figures in pdf and other formats at the same time?

I think in the preamble
opts_chunk$set(dev = c("pdf", "jpg"))
should do. Within a R-chunk of course.

Related

How to hide figures in knitr, but create them as png?

I am currently doing some statistical analysis in R and use knitr to generate results and an overview document.
There are some additional plots, which I want to be done and saved as a .png (with specified file name and location), but not included in the generated .html file (too many of them, and they are not at the end).
Using dev.copy(png, ...) works fine for generating the plots, but the figures appear in the .html. If I specify fig.keep=none the .png files are created, but blank.
Is there some way to do what I want?
This is from knitr website:
fig.show: ('asis'; character) how to show/arrange the plots; four
possible values are
asis: show plots exactly in places where they were
generated (as if the code were run in an R terminal)
hold: hold all
plots and output them in the very end of a code chunk
animate: wrap
all plots into an animation if there are mutiple plots in a chunk
hide: generate plot files but hide them in the output document
fig.show = 'hide' worked for me.

Unicode characters in plots to use in dynamic reports using R, Sweave and knitr

I have a problem properly displaying fonts in plots generated by ggplot2 in LaTeX reports generated by R studio in Sweave using knitr.
At first I was not able to properly generate pdfs with polish fonts but that problem was tackled in this post:
Unicode Characters in ggplot2 PDF Output
In short, the author adviced using Cairo package (in R) to generate plots using ggplot2.
This worked for me - once -> meaning I was able to generate a plot with polish characters, but when I am trying to use it in sweave document to generate LaTeX report using knitr like this:
<<pieniadze_graph,fig=TRUE,echo=FALSE>>=
library(Cairo)
cairo_pdf("TutorialExercisesPart2-pieniadze_graph.pdf")
plot1 <- qplot(expenditure, data = cas) + xlim(0, 8000) +
xlab(expression(paste("Pieniądze wydane na ucznia ($)"))) +
ylab("Liczba szkółńćźżś")
print(plot1)
#
I get an error.:
Running pdflatex on TutorialExercisesPart2.tex...failed
While investigating while that happend -> i found that the file that cairo is soppoused to generate is blank (there is a pdf file of a name given to cairo_pdf but it can not be opened with pdf viewer -> error cannot open text file)
Now one note is necessary: The cairo_pdf function requires file name to be set. So I give the pdf a name, that is required to be used later by the tex file in a format filename-chunk_name.pdf (So much for dynamic reports :P)
So I am not for the cairo_pdf option.
Is there a way to generate proper pdf files without cairo_pdf option?
I was not able to find anything more on this topic without the cairo-pdf...
When I delete the cairo part my tex file is generated nicely with an ugly looking dots labels PDF file in it...
Rather than opening a device like you do with calling cairo_pdf(), you should instruct knitr to use the device. Have a look at the knitr options and "dev" in particular. In summary, you need to
<<pieniadze_graph,fig=TRUE,echo=FALSE,dev='cairo_pdf'>>=
...
or to make it default for all chunks
opts_chunk$set(dev='cairo_pdf')
Ok I finally got it!
It really was a problem with Sweave coding in the chunk heading.
After #Matev's response I began testing the dev='cairo_pdf' -> but this did not change anything in the output.
Why? Because the
<<dev='cairo_pdf'>>=
#
is only interpreted by knitr Rnw file weaver!!! And I was using the Sweave weaver (this is set in the global options of R studio under Sweave section).
After recognising the not-so-obvious mistake (Because both Sweave and knitr use similar chunk heading script format) I seached what Leisch had to say about that in his Sweave Manual. This is his solution for everyone who has the same problem:
Put this code early in the document (after R libraries)
<<>>=
my.Swd <- function(name, width, height, ...)
grDevices::cairo_pdf(filename = paste(name, "pdf", sep = "."),
width = width, height = height)
#
You may now use the following code in seperate chunks
<<chunk_name,grdevice=my.Swd,fig=TRUE>>=
#
or as #Matev adviced globally set chunk options for the entire document (but again his answer was for the knitr weaver):
\SweaveOpts{grdevice=my.Swd}
Now You will get beautiful plots generated by the cairo_pdf device (base R device) which handles uniode fonts nicely!!! And they will get sweaved into Your dynamic reports like magic!
And I would like to thank Yihui for the knitr package which is GREAT!

Produce two plots from same chunk / statement in knitr

Is it possible to have plot-generating code output two versions of the same figure, at different sizes, from a .Rmd document? Either through chunk options (I didn't see anything that works directly here), or through a custom knitr hook? Preferably this would be done with the png device.
My motivation: I'd like to be able to output a figure at one size, which would fit inline in a compiled HTML document, and another figure that a user could show after clicking (think fancybox). I think I'll be able to handle the scripting necessary to make that work; however, first I need to convince R / knitr to output two versions of the figure.
Although I'm sure there are workarounds, it would be best if there was some way to get it to 'just work' behind the scenes, e.g. through a knitr hook. That way, we don't have to do anything special to the R code within a chunk, we just modify how we parse / evaluate that chunk.
Alternatively, one could use SVG graphics that would scale nicely, but then we lose the nice inference of good sizes for the plot labels, and vector graphics aren't great for plots with many many points.
I thought there was not a solution, and was about to say no to #baptiste, but got a hack in my mind soon. Below is an R Markdown example:
```{r test, dev='png', fig.ext=c('png', 'large.png'), fig.height=c(4, 10), fig.width=c(4, 10)}
library(ggplot2)
qplot(speed, dist, data=cars)
```
See the [original plot](figure/test.png) and
a [larger version](figure/test.large.png).
The reason I thought the vectorized version of dev would not work was: for dev=c('png', 'png'), the second png file will overwrite the first one because the figure filename is the same. Then I realized fig.ext was also vectorized, and a file extension like large.png does not really destroy the file extension png; this is why it is a hack.
Anyway, by vectorized versions of dev, fig.ext, fig.height, and fig.width, you can save the same plot to multiple versions. If you use a deterministic pattern for the figure file extensions, I think you can also cook up some JavaScript code to automatically attach fancy boxes onto images.
If you just need the small and large figure, can you just do:
<<plotSmall, fig.height=6, fig.width=8, out.width='.1\\textwidth'>>=
plot(...)
#
<<plotBig, fig.height=6, fig.width=8, out.width='.99\\textwidth'>>=
plot(...)
#
Or more simply:
<<plotBoth, fig.height=6, fig.width=8, out.width=c('.1\\textwidth', '.9\\textwidth')>>=
plot(...)
plot(...)
#
(sure you know this, but .Rmd is for LaTeX, while .Rhtml is for html - the .Rhtml syntax is slightly different.)

R2HTML or knitr for dynamic report generation?

I want to write an R function which processes some data and then automatically outputs an html report. This report should contain some fixed text, some text changing according to the underlying data and some figures.
What is the best way to go?
R2HTML or knitr?
What are the advantages of one over the other?
As far as I understood R2HTML allows me to build the html file sequentially while knitr already operates on an predefined .Rhtml file.
So, either use R2HTML or stitch and spin from knitr for on the fly report generation.
I would appreciate any suggestions or hints.
I grab this nice opportunity to promote pander a bit :)
This package was written for similar reasons like #Yihui's great knitr, although I wanted to let users really concentrate on the text and R code without dealing with chunk options etc. So letting users generate pretty HTML, pdf or even docx or odt output automatically with some predefined options.
These options affects e.g. the cache engine (handling dependencies without any chunk options) or the default plot options (let it be a "base" R graphics, lattice or ggplot2), so that you do no thave to set the color palette or the minor grid in each of your plots, just once - or live with the package defaults :)
The package captures the results (besides errors/warnings and other messages and the output) of all run R expression and can convert to Pandoc's markdown automatically. There are some helper functions that let you convert the resulting document written in a brew-like syntax automatically to e.g. HTML if you have pandoc installed, or export R objects to markdown/HTML/any other supported format in a live R session with a reference class.
Short demo:
brew file
Pandoc.brew('file_name.brew', output = 'foo.html', convert = 'html')
HTML output
knitr, every time. Handles graphics, lets you write your report with markdown instead of having to write html everywhere (if you want), caches things, makes coffee for you etc.
You can also build an HTML file sequentially as long as you have a decent text editor like Emacs/ESS or RStudio, etc. R2HTML is excellent in terms of its wide support to many R objects (see methods(HTML)), but I'll probably frown on RweaveHTML() due to its root Sweave().
That said, I think it may be a good idea to combine R2HTML and knitr, e.g.
# A LOESS Example
```{r loess-demo, results='asis'}
cars.lo <- loess(dist ~ speed, cars)
library(R2HTML)
HTML(cars.lo, file = '')
```
I was using the R Markdown syntax in the above example. The key is results='asis' which means to writing raw HTML code into the output.
I believe that you can also use Sweave to create HTML files, though I have heard that knitr is easier to use.

Redirecting R output and graphs

I use Sweave and LaTex to create reports from R output and graphs. But sometime it is required to have graphs in editable format. I tried R2wd package but it doesn't seem very flexible with ggplot2. I'd highly appreciate if someone point out me some efficient ways. Thanks
It really depends what you mean by "editable", and what kinds of files/endpoints you're talking about. There are a lot of discussions out there (e.g. this R-help thread from 2006) about (1) the best options for generating figures to embed in Word (or PowerPoint, which is pretty much the same question) and (2) the best options for figures that can be edited (by which I mean that they can be modified by non-R-users, not just moved from file to file). The general conclusions I have seen are:
PDF files: vector format, editable in Adobe Illustrator ($$$), only sorta-kinda-embeddable in MS Office documents
Windows metafiles or extended metafiles (WMF/EMF): vector format, very limited support outside of the Windows platform. Somewhat wonky format, but MS Office-native. Will certainly have limited support for things like alpha channels (transparency).
SVG: vector format. Very modern, editable in Inkscape (don't know where else), not particularly MS Office-compatible (I think). (Generatable at least via the Cairo package.)
PNG: raster format, but very compact (you can make the resolution absurdly large and still have a reasonably small output file); probably the easiest/lowest-common-denominator solution if you only need portability and not editability.
As of R 2.13.0, Sweave can automatically generate both PDF and PNG files on the fly for each figure chunk. If this is saved as document foo.Rnw:
\documentclass{article}
\begin{document}
\SweaveOpts{png=TRUE,pdf=TRUE,eps=FALSE}
<<fig1,fig=TRUE>>=
plot(1:5,1:5,col=1:5,pch=16)
#
\end{document}
... then after Sweaveing your directory will contain the files foo-fig1.png and foo-fig1.pdf. I don't know if that answers your question, but your question isn't entirely clear ...
The package pgfSweave links together Sweave with tikzDevice. tikzDevice uses the LaTeX tikz package to put the instructions to draw a plot into LaTeX code. So you can copy the resulting code from one file to another. pgfSweave also adds some handy features like cacheing.
You could also just output PDFs of your plots with pdf() and then insert the LaTeX code to load those plots as figures. You lose the automated file management of Sweave that way though.

Resources