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))
```
I'm trying to knit to pdf a file with Lithuanian characters like ąčęėįšųž in RStudio from .Rmd file. While knitting to html works properly and the ggplot title has the Lithuanian characters, when knitting to pdf ggplot does create warnings and dismisses these characters.
Reproducible example:
---
title: "Untitled"
output:
pdf_document:
includes:
in_header: header_lt_text.txt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
## Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
I pass the header_lt_text.txt with follwoing arguments:
\usepackage[utf8]{inputenc}
\usepackage[L7x]{fontenc}
\usepackage[lithuanian]{babel}
\usepackage{setspace}
\onehalfspacing
Any suggestions on how to make ggplot create correct labels?
The problem is with the pdf device and is only apparent when saving the picture as pdf (which you want because it looks much, much better). This is why it seems to "work" in some cases: the image is not rendered as pdf but e.g. as png. Thanks to #Konrad for correctly identifying the source of the problem.
To solve this, you need to pass the correct encoding to the pdf device.
Fortunately, the pdf device (?pdf) takes an encoding argument and there is a chunk option to pass arguments to the device: dev.args
On Windows, an appropriate encoding is CP1257.enc (Baltic):
```{r dev="pdf", dev.args=list(encoding="CP1257.enc")}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
You can see the other encodings available out of the box with: list.files(system.file("enc", package = "grDevices"))
Works well on my linux machine:
Alternatively, if you're happy to get png images inserted in the pdf, you can simply use dev="png" in your chunk option. Doesn't look as good though.
System Details
RStudio Version : 1.1.442,
OS Version : Windows 7 Professional,
R Version : 3.4.4,
rmarkdown : 1.9,
knitr : 1.20,
tufte : 0.3
Steps to reproduce the problem
Knit to tufte_book the following default template. It won't knit and instead I get an "Error: pandoc document conversion failed with error 5". I have reinstalled R Studio, updated to R 3.4.4 and updated all my packages with update.packages().
Also - I am able to knit to tufte_html and tufte_handout, it's just tufte_book that gives the error.
---
title: "Tufte Handout"
subtitle: "An implementation in R Markdown"
author: "JJ Allaire and Yihui Xie"
date: "`r Sys.Date()`"
output:
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_html: default
bibliography: skeleton.bib
link-citations: yes
---
```{r setup, include=FALSE}
library(tufte)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
```
# Introduction
The Tufte handout style is a style that Edward Tufte uses in his books and handouts. Tufte's style is known for its extensive use of sidenotes, tight integration of graphics with text, and well-set typography. This style has been implemented in LaTeX and HTML/CSS^[See Github repositories [tufte-latex](https://github.com/tufte-latex/tufte-latex) and [tufte-css](https://github.com/edwardtufte/tufte-css)], respectively. We have ported both implementations into the [**tufte** package](https://github.com/rstudio/tufte). If you want LaTeX/PDF output, you may use the `tufte_handout` format for handouts, and `tufte_book` for books. For HTML output, use `tufte_html`. These formats can be either specified in the YAML metadata at the beginning of an R Markdown document (see an example below), or passed to the `rmarkdown::render()` function. See #R-rmarkdown more information about **rmarkdown**.
```yaml
---
title: "An Example Using the Tufte Style"
author: "John Smith"
output:
tufte::tufte_handout: default
tufte::tufte_html: default
---
```
There are two goals of this package:
1. To produce both PDF and HTML output with similar styles from the same R Markdown document;
1. To provide simple syntax to write elements of the Tufte style such as side notes and margin figures, e.g. when you want a margin figure, all you need to do is the chunk option `fig.margin = TRUE`, and we will take care of the details for you, so you never need to think about `\begin{marginfigure} \end{marginfigure}` or `<span class="marginfigure"> </span>`; the LaTeX and HTML code under the hood may be complicated, but you never need to learn or write such code.
If you have any feature requests or find bugs in **tufte**, please do not hesitate to file them to https://github.com/rstudio/tufte/issues. For general questions, you may ask them on StackOverflow: http://stackoverflow.com/tags/rmarkdown.
# Headings
This style provides first and second-level headings (that is, `#` and `##`), demonstrated in the next section. You may get unexpected output if you try to use `###` and smaller headings.
`r newthought('In his later books')`^[[Beautiful Evidence](http://www.edwardtufte.com/tufte/books_be)], Tufte starts each section with a bit of vertical space, a non-indented paragraph, and sets the first few words of the sentence in small caps. To accomplish this using this style, call the `newthought()` function in **tufte** in an _inline R expression_ `` `r ` `` as demonstrated at the beginning of this paragraph.^[Note you should not assume **tufte** has been attached to your R session. You should either `library(tufte)` in your R Markdown document before you call `newthought()`, or use `tufte::newthought()`.]
# Figures
## Margin Figures
Images and graphics play an integral role in Tufte's work. To place figures in the margin you can use the **knitr** chunk option `fig.margin = TRUE`. For example:
```{r fig-margin, fig.margin = TRUE, fig.cap = "MPG vs horsepower, colored by transmission.", fig.width=3.5, fig.height=3.5, cache=TRUE, message=FALSE}
library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
geom_point() + geom_smooth() +
theme(legend.position = 'bottom')
```
Note the use of the `fig.cap` chunk option to provide a figure caption. You can adjust the proportions of figures using the `fig.width` and `fig.height` chunk options. These are specified in inches, and will be automatically scaled down to fit within the handout margin.
## Arbitrary Margin Content
In fact, you can include anything in the margin using the **knitr** engine named `marginfigure`. Unlike R code chunks ```` ```{r} ````, you write a chunk starting with ```` ```{marginfigure} ```` instead, then put the content in the chunk. See an example on the right about the first fundamental theorem of calculus.
```{marginfigure}
We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$:
$$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$
```
For the sake of portability between LaTeX and HTML, you should keep the margin content as simple as possible (syntax-wise) in the `marginefigure` blocks. You may use simple Markdown syntax like `**bold**` and `_italic_` text, but please refrain from using footnotes, citations, or block-level elements (e.g. blockquotes and lists) there.
Note: if you set `echo = FALSE` in your global chunk options, you will have to add `echo = TRUE` to the chunk to display a margin figure, for example ```` ```{marginfigure, echo = TRUE} ````.
## Full Width Figures
You can arrange for figures to span across the entire page by using the chunk option `fig.fullwidth = TRUE`.
```{r fig-fullwidth, fig.width = 10, fig.height = 2, fig.fullwidth = TRUE, fig.cap = "A full width figure.", warning=FALSE, message=FALSE, cache=TRUE}
ggplot(diamonds, aes(carat, price)) + geom_smooth() +
facet_grid(~ cut)
```
Other chunk options related to figures can still be used, such as `fig.width`, `fig.cap`, `out.width`, and so on. For full width figures, usually `fig.width` is large and `fig.height` is small. In the above example, the plot size is $10 \times 2$.
## Main Column Figures
Besides margin and full width figures, you can of course also include figures constrained to the main column. This is the default type of figures in the LaTeX/HTML output.
```{r fig-main, fig.cap = "A figure in the main column.", cache=TRUE}
ggplot(diamonds, aes(cut, price)) + geom_boxplot()
```
# Sidenotes
One of the most prominent and distinctive features of this style is the extensive use of sidenotes. There is a wide margin to provide ample room for sidenotes and small figures. Any use of a footnote will automatically be converted to a sidenote. ^[This is a sidenote that was entered using a footnote.]
If you'd like to place ancillary information in the margin without the sidenote mark (the superscript number), you can use the `margin_note()` function from **tufte** in an inline R expression. `r margin_note("This is a margin note. Notice that there is no number preceding the note.")` This function does not process the text with Pandoc, so Markdown syntax will not work here. If you need to write anything in Markdown syntax, please use the `marginfigure` block described previously.
# References
References can be displayed as margin notes for HTML output. For example, we can cite R here [#R-base]. To enable this feature, you must set `link-citations: yes` in the YAML metadata, and the version of `pandoc-citeproc` should be at least 0.7.2. You can always install your own version of Pandoc from http://pandoc.org/installing.html if the version is not sufficient. To check the version of `pandoc-citeproc` in your system, you may run this in R:
```{r eval=FALSE}
system2('pandoc-citeproc', '--version')
```
If your version of `pandoc-citeproc` is too low, or you did not set `link-citations: yes` in YAML, references in the HTML output will be placed at the end of the output document.
# Tables
You can use the `kable()` function from the **knitr** package to format tables that integrate well with the rest of the Tufte handout style. The table captions are placed in the margin like figures in the HTML output.
```{r}
knitr::kable(
mtcars[1:6, 1:6], caption = 'A subset of mtcars.'
)
```
# Block Quotes
We know from the Markdown syntax that paragraphs that start with `>` are converted to block quotes. If you want to add a right-aligned footer for the quote, you may use the function `quote_footer()` from **tufte** in an inline R expression. Here is an example:
> "If it weren't for my lawyer, I'd still be in prison. It went a lot faster with two people digging."
>
> `r tufte::quote_footer('--- Joe Martin')`
Without using `quote_footer()`, it looks like this (the second line is just a normal paragraph):
> "Great people talk about ideas, average people talk about things, and small people talk about wine."
>
> --- Fran Lebowitz
# Responsiveness
The HTML page is responsive in the sense that when the page width is smaller than 760px, sidenotes and margin notes will be hidden by default. For sidenotes, you can click their numbers (the superscripts) to toggle their visibility. For margin notes, you may click the circled plus signs to toggle visibility.
# More Examples
The rest of this document consists of a few test cases to make sure everything still works well in slightly more complicated scenarios. First we generate two plots in one figure environment with the chunk option `fig.show = 'hold'`:
```{r fig-two-together, fig.cap="Two plots in one figure environment.", fig.show='hold', cache=TRUE, message=FALSE}
p <- ggplot(mtcars2, aes(hp, mpg, color = am)) +
geom_point()
p
p + geom_smooth()
```
Then two plots in separate figure environments (the code is identical to the previous code chunk, but the chunk option is the default `fig.show = 'asis'` now):
```{r fig-two-separate, ref.label='fig-two-together', fig.cap=sprintf("Two plots in separate figure environments (the %s plot).", c("first", "second")), cache=TRUE, message=FALSE}
```
You may have noticed that the two figures have different captions, and that is because we used a character vector of length 2 for the chunk option `fig.cap` (something like `fig.cap = c('first plot', 'second plot')`).
Next we show multiple plots in margin figures. Similarly, two plots in the same figure environment in the margin:
```{r fig-margin-together, fig.margin=TRUE, fig.show='hold', fig.cap="Two plots in one figure environment in the margin.", fig.width=3.5, fig.height=2.5, cache=TRUE}
p
p + geom_smooth(method = 'lm')
```
Then two plots from the same code chunk placed in different figure environments:
```{r fig-margin-separate, fig.margin=TRUE, fig.cap=sprintf("Two plots in separate figure environments in the margin (the %s plot).", c("first", "second")), fig.width=3.5, fig.height=2.5, cache=TRUE}
knitr::kable(head(iris, 15))
p
knitr::kable(head(iris, 12))
p + geom_smooth(method = 'lm')
knitr::kable(head(iris, 5))
```
We blended some tables in the above code chunk only as _placeholders_ to make sure there is enough vertical space among the margin figures, otherwise they will be stacked tightly together. For a practical document, you should not insert too many margin figures consecutively and make the margin crowded.
You do not have to assign captions to figures. We show three figures with no captions below in the margin, in the main column, and in full width, respectively.
```{r fig-nocap-margin, fig.margin=TRUE, fig.width=3.5, fig.height=2, cache=TRUE}
# a boxplot of weight vs transmission; this figure
# will be placed in the margin
ggplot(mtcars2, aes(am, wt)) + geom_boxplot() +
coord_flip()
```
```{r fig-nocap-main, cache=TRUE}
# a figure in the main column
p <- ggplot(mtcars, aes(wt, hp)) + geom_point()
p
```
```{r fig-nocap-fullwidth, fig.fullwidth=TRUE, fig.width=10, fig.height=3, cache=TRUE}
# a fullwidth figure
p + geom_smooth(method = 'lm') + facet_grid(~ gear)
```
# Some Notes on Tufte CSS
There are a few other things in Tufte CSS that we have not mentioned so far. If you prefer `r sans_serif('sans-serif fonts')`, use the function `sans_serif()` in **tufte**. For epigraphs, you may use a pair of underscores to make the paragraph italic in a block quote, e.g.
> _I can win an argument on any topic, against any opponent. People know this, and steer clear of me at parties. Often, as a sign of their great respect, they don't even invite me._
>
> `r quote_footer('--- Dave Barry')`
We hope you will enjoy the simplicity of R Markdown and this R package, and we sincerely thank the authors of the Tufte-CSS and Tufte-LaTeX projects for developing the beautiful CSS and LaTeX classes. Our **tufte** package would not have been possible without their heavy lifting.
You can turn on/off some features of the Tufte style in HTML output. The default features enabled are:
```yaml
output:
tufte::tufte_html:
tufte_features: ["fonts", "background", "italics"]
```
If you do not want the page background to be lightyellow, you can remove `background` from `tufte_features`. You can also customize the style of the HTML page via a CSS file. For example, if you do not want the subtitle to be italic, you can define
```css
h3.subtitle em {
font-style: normal;
}
```
in, say, a CSS file `my_style.css` (under the same directory of your Rmd document), and apply it to your HTML output via the `css` option, e.g.,
```yaml
output:
tufte::tufte_html:
tufte_features: ["fonts", "background"]
css: "my_style.css"
```
There is also a variant of the Tufte style in HTML/CSS named "[Envisoned CSS](http://nogginfuel.com/envisioned-css/)". This style can be used by specifying the argument `tufte_variant = 'envisioned'` in `tufte_html()`^[The actual Envisioned CSS was not used in the **tufte** package. We only changed the fonts, background color, and text color based on the default Tufte style.], e.g.
```yaml
output:
tufte::tufte_html:
tufte_variant: "envisioned"
```
To see the R Markdown source of this example document, you may follow [this link to Github](https://github.com/rstudio/tufte/raw/master/inst/rmarkdown/templates/tufte_html/skeleton/skeleton.Rmd), use the wizard in RStudio IDE (`File -> New File -> R Markdown -> From Template`), or open the Rmd file in the package:
```{r eval=FALSE}
file.edit(
tufte:::template_resources(
'tufte_html', '..', 'skeleton', 'skeleton.Rmd'
)
)
```
This document is also available in [Chinese](http://rstudio.github.io/tufte/cn/), and its `envisioned` style can be found [here](http://rstudio.github.io/tufte/envisioned/).
```{r bib, include=FALSE}
# create a bib file for the R packages used in this document
knitr::write_bib(c('base', 'rmarkdown'), file = 'skeleton.bib')
```
The following Rmarkdown renders the plotly 3D graph in HTML, but not in PDF.
Testing plotly
```{r}
library(plotly)
p <- plot_ly(data=iris, x=~Sepal.Length, y=~Sepal.Width, z=~Petal.Length,
color=~Species, symbols=c(0,1), type="scatter3d", mode="markers")
p
```
A snapshot of the graph appears as follows:
According to the plotly help page:
If you are using rmarkdown with HTML output, printing a plotly object in a code chunk will result in an interactive HTML graph. When using rmarkdown with non-HTML output, printing a plotly object will result in a png screenshot of the graph.
Is there a way to render the plotly graph in a PDF?
Note: The error from rmarkdown::render() is:
Error: Functions that produce HTML output found in document targeting latex output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: yes
Note however that the HTML output will not be visible in non-HTML formats.
I have created a little workaround, which saves the plotly images locally as png-file and imports it back to the RMD file.
You need the package webshot, which you can load via:
install.packages("webshot")
Further more, you need to install phantomjs via
webshot::install_phantomjs()
Then (when phantomjs is in your PATH), you can create your RMD file:
---
title: "Untitled"
output: pdf_document
---
```{r}
library(plotly)
p <- plot_ly(economics, x = ~date, y = ~unemploy / pop)
tmpFile <- tempfile(fileext = ".png")
export(p, file = tmpFile)
```
![Caption for the picture.](`r tmpFile`)
This works for me .. perhaps it's a workaround for you, too!
As #hrbrmstr commented, export() previously didn't support WebGL at all, but more recent versions support exporting to png via RSelenium (see help(export, package = "plotly")). If you need pdf export, you'll have to pay for a cloud account -- https://plot.ly/products/cloud/
Same issue with R markdown compile error:. You need to choose what format you want to KNIT to, tried to look at mine.
---
title: "<img src='www/binary-logo.jpg' width='240'>"
subtitle: "[<span style='color:blue'>binary.com</span>](https://github.com/englianhu/binary.com-interview-question) Interview Question I"
author: "[<span style='color:blue'>®γσ, Lian Hu</span>](https://englianhu.github.io/) <img src='www/ENG.jpg' width='24'> <img src='www/RYO.jpg' width='24'>白戸則道®"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
toc: yes
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
link-citations: yes
---
What I do so that rendering to PDF's work but you can still have the interactive plots in other knit types and in rmarkdown files in r studio is:
this goes in the setup block (or really, anywhere early in the file):
is_pdf <- try (("pdf_document" %in% rmarkdown::all_output_formats(knitr::current_input())), silent=TRUE)
is_pdf <- (is_pdf == TRUE)
then this is used to render any plotly plot based on what kind of document you are creating:
if (is_pdf) { export(base_plot) } else {base_plot}
in the example base_plot is the name of the plot.
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