Knitr with gridSVG - r

Does anybody use gridSVG in Knitr? I found package "gridSVG" provide a device named "gridsvg" and I've written code as follows.
```{r message=FALSE, echo=FALSE, warning=FALSE, results='hide', dev='gridsvg', fig.ext='svg'}
analysis.runner.result.plot(result, score.table, info.table) # which produces a gpplot
```
When I click "Knitr HTML", I got:
pandoc.exe: Could not find data file
AnalysisReport_files/figure-html/unnamed-chunk-61.svg pandoc document conversion failed
It seems that the gridsvg didn't produce svg file. I've searched the internet but failed to find any example that uses gridSVG in knitr.
How should I modify the code? (P.S. due to the render quality under windows, I don't want to use the default 'svg' device)
Thanks!

Update: with knitr >= v1.40, you can ignore the answer below and simply use the chunk option dev = 'gridSVG'.
Because gridSVG::gridsvg() is not a standard R graphics device, you cannot use the dev chunk option in knitr. The only way at the moment is to manually save the plots, and use a chunk hook to write the plots to your output (see the knitr graphics manual). Here is an example:
---
title: Save plots using gridSVG and knitr
author: Yihui Xie
output:
html_document: default
---
Set up a chunk hook for manually saved plots.
```{r setup}
library(knitr)
knit_hooks$set(custom.plot = hook_plot_custom)
```
A single plot.
```{r test-a, fig.keep='none', fig.ext='svg', custom.plot=TRUE}
library(ggplot2)
qplot(speed, dist, data = cars)
gridSVG::grid.export(fig_path('.svg'))
```
Multiple plots.
```{r test-b, fig.keep='none', fig.ext='svg', custom.plot=TRUE, fig.num=2, message=FALSE}
library(ggplot2)
p = qplot(speed, dist, data = cars)
p + geom_smooth()
gridSVG::grid.export(fig_path('svg', number = 1))
p + geom_jitter()
gridSVG::grid.export(fig_path('svg', number = 2))
```
See the source document of this post at
http://stackoverflow.com/q/23852753/559676
See output at http://rpubs.com/yihui/knitr-gridsvg

Related

Write pdf to figure folder, but delete pngs

This is a follow-up question about this answer. I have set the knitr chunk options to output a png and pdf version of plots in a folder, as well as use the pngs in the knitted report.
However, I'd only like to keep the pdf version of the figure and discard the png file. Is there a knitr-equivalent of on.exit() to clean up the pngs after knitting? Or an option I overlooked?
With the rmarkdown document below, how do I automatically clean up the png version of the plot after knitting? (Or not produce it as a standalone file in the first place)
---
title: "Untitled"
author: "Me"
date: "21/10/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
dev = c("png", "pdf"),
fig.path = here::here(
"figures",
gsub("\\.Rmd$", "\\\\", basename(knitr::current_input()))
)
)
```
```{r my_plot}
library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
geom_point()
```
That is not exactly what you are looking for, but manually removing eval=FALSE from the following chunk, deletes the wanted files:
```{r eval=FALSE, include=FALSE}
fList <- dir("figures")
fList <- fList[stringr::str_detect(fList,"\\.png$")]
file.remove(paste0("figures/",fList))
```

Using LaTeX animate package in RMarkdown

I would like to generate an animated graphic in PDF using the LaTeX animate package.
Code
---
title: "test_animations"
author: "Colours"
date: "27/10/2017"
output:
pdf_document:
includes:
in_header: header_ani.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
pacman::p_load(gganimate, gapminder, ggplot2)
```
## Test animations
```{r sample_ani, fig.show='animate', message=FALSE, warning=FALSE}
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
geom_point(aes(frame = year), color = "red") +
scale_x_log10()
gganimate(p2, saver = "gif")
```
header_ani.tex
\usepackage{animate}
Problem
Warning: Ignoring unknown aesthetics: frame
Quitting from lines 20-25 (second_animation.Rmd) Error: Could not
find ffmpeg command. You should either change the animation.fun hook
option or install ffmpeg with libvpx enabled. Execution halted
Notes
Why the reference to ffmpeg. According to the knitr documentation:
When the chunk option fig.show='animate' and there are multiple plots
produced from a code chunk, all plots will be combined to an
animation. For LaTeX output, the LaTeX package animate is used to
create animations in PDF. For HTML/Markdown output, by default FFmpeg
is used to create a WebM video. Note you have to enable the libvpx
support when installing FFmpeg. Linux and Windows users can just
follow the download links on the FFmpeg website (libvpx has been
enabled in the binaries). For OS X users, you can install FFmpeg via
Homebrew
ffmpeg should be used in conversion to html. Is it because of the RMarkdown's pipeline?
(RStudio: RMarkdown)
that forces use of ffmpeg somewhere along the line?
Question
Is it possible to make use of the animate package in a RMarkdown document and avoid ffmpeg so the obtained PDF has the following component with conrtols offred by the animate package.
(Not the chart I want to generate but shows how the animated graphic should be embedded in the PDF, taken from the animate package documentation referenced above.)
Drawing on a similar answer (Plot animation in knitr rmarkdown) and a LaTeX-related discussion I have came up with the following solution:
---
title: "test_animations"
author: "Colours"
date: "27/10/2017"
classoption: landscape
output:
pdf_document:
keep_tex: true
includes:
in_header: header_ani.tex
---
```{r setup, include=FALSE}
Vectorize(require)(package = c("knitr"),
character.only = TRUE)
opts_chunk$set(echo = FALSE,
cache = TRUE)
pacman::p_load(gganimate, gapminder, ggplot2)
```
## Test animations
```{r sample_ani, message=TRUE, warning=TRUE, echo=TRUE, }
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
geom_point(aes(frame = year), color = "red") +
scale_x_log10()
gganimate(p2, filename = "animation2.gif", title_frame = TRUE) -> amimate
```
<!-- Notes on the answer: https://tex.stackexchange.com/a/240387/123504 -->
```{r convert_shele, echo=TRUE, message=TRUE, warning=TRUE, paged.print=FALSE}
# Extra options for resize can be added
system(command = "convert -coalesce animation2.gif something.png")
```
\animategraphics[loop,controls,width=\linewidth]{12}{something-}{0}{12}
# Latex code generating animation
Figures 0 - 12 should reflect frames
~~~
\animategraphics[loop,controls,width=\linewidth]{12}{something-}{0}{12}
~~~
The header file is as in question. The code generates and animated graph with the required controls.
Preview
Snapshot of generated animation with the controls available.
Notes
The code makes use of the external convert command. I reckon that this is not optimal as it involves converting the graph back and forth.
As a consequence of above, the values in {12}{something-}{0}{12} have to be set manually with the first figure reflecting frame rate (decreasing will slow down the animation) something- corresponds to files generated via convert that are named something-0.png ... something-n.png and {0}{12} corresponds to the file numbers.

Changing page size within Rmarkdown document

I have a very large phylogenetic tree that I'd quite like to insert into a supplementary material I'm writing using Rmarkdown and knitr. I dislike splitting trees across pages and I doubt anybody would print this out anyway so I thought I'd just have a large page in the middle of the pdf I'm generating.
The question is how do I change page size for one page in an otherwise A4 document? I'm pretty new to knitr and I've found global paper size options but I'm struggling to find ways of setting up what would be the equivalent of sections in Word.
(Update) Hi does anybody else have a suggestion? I tried the pdfpages package but this seems to result in an equally small figure on a page the size of the pdf that is being pasted in i.e. if I make a 20in by 20in pdf figure then paste the page in using \includepdf then I get a 20in by 20in page with a much smaller figure on it (the same as the \eject example above). It seems like knitr or Latex is forcing the graphics to have a specific size regardless of page size. Any ideas? Here's a reproducible example:
---
title: "Test"
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{pdfpages}
---
```{r setup, include=FALSE}
require(knitr)
knitr::opts_chunk$set(echo = FALSE,
warning=FALSE,
message=FALSE,
dev = 'pdf',
fig.align='center')
```
```{r mtcars, echo=FALSE}
library(ggplot2)
pdf("myplot.pdf", width=20, height=20)
ggplot(mtcars, aes(mpg, wt)) + geom_point()
dev.off()
```
#Here's some text on a normal page, the following page is bigger but has a tiny figure.
\newpage
\includepdf[fitpaper=true]{myplot.pdf}
You should be able to use \ejectpage like this:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
\eject \pdfpagewidth=20in \pdfpageheight=20in
```{r mtcars}
library(ggplot2)
ggplot(mtcars, aes(mpg, wt)) + geom_point()
```
\eject \pdfpagewidth=210mm \pdfpageheight=297mm
Back
(I can only remember the A4 height in mm for some reason)
I have just faced the same struggle when dealing with a large phylogenetic tree.
Based on hrbrmstr's answer, I came up with the snippet below.
The trick is to make knitr generate the figure but not include it in the intermediate .tex right away (hence fig.show="hide"). Then, because figure paths are predictable, you can insert it with some latex after the code chunk.
However, the new page height is not taken into account when positioning page numbers, so they tend to be printed over your image. I have tried to overcome this behavior multiple times, but in the end I simply turned them off with \thispagestyle{empty}.
---
output: pdf_document
---
```{r fig_name, fig.show="hide", fig.height=30, fig.width=7}
plot(1)
```
\clearpage
\thispagestyle{empty}
\pdfpageheight=33in
\begin{figure}[p]
\caption{This is your caption.}\label{fig:fig_name}
{\centering \includegraphics[height=30in, keepaspectratio]{main_files/figure-latex/fig_name-1} }
\end{figure}
\clearpage
\pdfpageheight=11in

Embedding fonts in ggplot2 charts in rmarkdown documents

I would like to use non-standard fonts in a ggplot2 chart which I then embed in an rmarkdown document, which get knitted into a PDF. My current workflow is to specify the font in the chart, then knit, then run extrafonts::embed_fonts on the created PDF. My question is: can I specify directly in the rmarkdown document that fonts should be embedded in the outputted PDF?
Minimal example:
---
title: "Untitled"
output: beamer_presentation
---
```{r}
library(extrafont)
library(ggplot2)
loadfonts()
qplot(iris$Sepal.Length) + theme_light(base_family = "CM Roman")
```
knitr::knit2pdf("test.rmd")
embed_fonts("test.pdf")
If you set the graphics device to "cairo_pdf" the fonts will be embedded. You can do this for individual chunks or for the whole document using knitr::opts_chunk$set
I used a really obviously different font below so that it was clear the fonts were really being set.
The package is called "extrafont" not "extrafonts"
---
title: "Untitled"
output: beamer_presentation
---
```{r, echo=FALSE, message = FALSE}
knitr::opts_chunk$set(warning=FALSE, message=FALSE, echo = FALSE, dev = "cairo_pdf")
```
```{r}
library(extrafont)
library(ggplot2)
loadfonts()
```
##
```{r, fig.width = 5}
qplot(iris$Sepal.Length) + theme_light(base_family = "Vladimir Script")
```

knitr plots, labels, and captions within one chunk - .Rmd files

Jallen produced a solution for producing knitr plots, labels, and captions within one chunk - for Rnw files.
knitr plots, labels, and captions within one chunk
This works nicely for .Rnw but I can't make it work for .Rmd, don't see what is going wrong...
---
output:
pdf_document:
fig_caption: yes
fig_crop: no
---
```{r startup,echo=FALSE,results='hide',message=FALSE,tidy=FALSE,warning=FALSE,fig.keep='all',comment=NA}
require(knitr)
require(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA,
tidy=FALSE,
warning=FALSE,
message=FALSE,
echo=FALSE,
dpi=600,
fig.width=6.75, fig.height=4, # Default figure widths
dev=c("pdf",'tiff'),
dev.args=list(pdf=list(NULL),tiff=list(compression='lzw')),
error=FALSE)
```
```{r plotloop,results='asis'}
for(x in seq(1,20)){
x1<-data.frame(x=seq(1,10),y=seq(1,10))
plt<-ggplot(data=x1,aes(x,y))+geom_point()
figLabel=paste('Figure',x,sep='')
capt<-paste('Caption for fig.',x)
cat(knit(text=(paste("```{r ",figLabel,",fig.pos='h',fig.cap='",capt,"'}\nplt\n```",sep=''))))
cat('\\newpage')
plot.knit function in knitr plots, labels, and captions within one chunk can be modified to account for the syntax of markdown as opposed to latex. plot.knit.md becomes
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
This works in the following markdown doc.
---
title: "plot.knit.md demo"
author: "Joel Allen"
date: "04/23/2015"
output:
html_document: default
pdf_document:
fig_caption: yes
---
This is an R Markdown document to demonstrate the generation of self-contained code chunks in a markdown file. It is particularly useful for situations where multiple plots are generated in a single code chunk allowing for dynamic label and caption support.
This example draws on
http://stackoverflow.com/questions/21685885/knitr-plots-labels-and-captions-within-one-chunk
in response to
https://stackoverflow.com/questions/27443019/knitr-plots-labels-and-captions-within-one-chunk-rmd-files
Items to note:
#. output pdf_document fig_caption option must be set to yes
#. plot.knit has been modified to plot.knit.md to account for the different syntax needed.
```{r, echo=FALSE,results='asis'}
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
require(ggplot2)
cars.p<-ggplot(cars,aes(x=speed,y=dist))+
geom_point()
plot.knit.md(chunkLabel="carsPlot",capt="this is a caption for the cars plot",plt=cars.p)
```
One thing to figure out though is the attachment of labels...

Resources