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))
```
Related
I have two RMarkdown files. main.Rmd which is the main file which is rendered as well as example.Rmd which holds a longer example and is used elsewhere (hence it lives in its own document).
I want to include example.Rmd in the main.Rmd file with code highlighting of its RMarkdown code but the code of example.Rmd does not need to be executed, as if I set eval=FALSE and copied all code into the chunk by hand.
An example MWE is
main.Rmd
---
title: This is main.rmd
output: html_document
---
```{r}
# attempt that doesnt work
cat(readLines("example.Rmd"), sep = "\n")
```
and in example.Rmd
---
title: This is example.rmd
output: html_document
---
```{r}
# code that is not executed but shown in main.Rmd
data <- ...
```
Set eval=FALSE in the example.Rmd file and then include it in main.Rmd using child chunk option.
example.Rmd
---
title: This is example.Rmd
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```
```{r}
# This is from example.Rmd
x <- rnorm(10)
y <- rnorm(10)
lm(y ~ x)
```
```{r}
# some comments
print("This is from example.Rmd")
```
main.Rmd
---
title: This is main.Rmd
output:
html_document:
highlight: haddock
---
```{r example, child="example.Rmd"}
```
Edit
To show full source-code of the Rmarkdown file, one possible option could be reading that Rmd file and then cat it with chunk option comment="".
Now about the syntax highlighting; there's a chunk option class.output with which it is possible to specify a language name for which pandoc supports syntax highlighting.
You can get the list of language names for which pandoc has syntax highlighting support by running the following,
pandoc --list-highlight-languages
(Note, if you don't have pandoc installed separately, you can also use the pandoc installed with Rstudio itself. Run rmarkdown::pandoc_exec() to get the pandoc executable path)
Now, the file we are trying to include actually contains not just R code, but also markdown and yaml syntaxes. So it's a kind of mixed thing and pandoc has no syntax highlighting support out of the box for this. Still I have chosen c as syntax highlighting language just to show the possibility. (Also tried r, but syntax-highlighting is not so distinctive)
---
title: This is main.Rmd
output:
html_document:
highlight: tango
---
## Rmarkdown
```{r example, echo=FALSE, class.output="c", comment=""}
cat(readLines("example.Rmd"), sep = "\n")
```
But still if you want a specific syntax-highlighting for Rmarkdown, you can actually create one. See here from the pandoc documentation itself and also this answer on SO about this.
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
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")
```
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...
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