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.
Related
I have a code chunk in an R Markdown file, that generates multiple ggplots in a for loop. The chunk (pseudo-code) is called like so:
```{r print_data, results='asis'}
print.all.results()
```
Inside the print.all.results(), the ggplots are generated and printed using standard print(plot) (see below).
This works without any problems (HTML as well as PDF).
For the PDF outputs, I would now like to switch to landscape mode using \usepackage{pdflscape} (already added to the preamble).
I then tried to switch to the landscape environment in the R code within the chunk. Based on this question and this question, I added the following lines within the print.all.results() function:
cat("\\begin{landscape}")
for (index in vector) {
plot <- generateplot()
print(plot)
}
cat("\\end{landscape}")
However, as soon as I do this, the knitting of the document fails. In the intermediary .tex file, the graphics are not called via \includegraphics anymore but rather, they are linked via the markdown call to them (which of course fails in a tex compile):
\begin{landscape}
![](rmddocument_files/figure-latex/print_data-1.pdf)<!-- -->
![](rmddocument_files/figure-latex/print_data-2.pdf)<!-- -->
![](rmddocument_files/figure-latex/print_data-3.pdf)<!-- -->
\end{landscape}
I have also tried multiple variations using pander but did not find a working solution.
I am now confused why a) the inclusion of the environment suddenly changes the behavior of the print for the plot and b) something comparable seems to work in example 2.
Is this a bug? Could this be a problem with my build pipeline? What could be a solution?
NB: I can't generate the latex code in the .rmd - it has to happen within the code chunk.
An MWE would be this (easiest run trough Knit Button in R Studio; the .tex files and pdfs from the plot are generated in the same folder):
---
title: "Landscape Problem"
author: "Dom42"
date: "`r Sys.Date()`"
output:
pdf_document:
extra_dependencies: pdflscape
keep_tex: yes
---
```{r function}
print.plots.landscape <- function() {
cat("\\begin{landscape}")
for (i in 1:3) {
temp.plot <- plot(hist(mtcars[,i]))
print(temp.plot)
}
cat("\\end{landscape}")
}
```
```{r call, results='asis'}
print.plots.landscape()
```
This Example produces a .tex that contains
\begin{landscape}![](landscape-example_files/figure-latex/call-1.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-2.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-3.pdf)<!-- --> NULL
\end{landscape}
However, what should actually come out of it (works, if uncommenting the cats in the for-loop):
\includegraphics{landscape-example_files/figure-latex/call-1.pdf} NULL
\includegraphics{landscape-example_files/figure-latex/call-2.pdf} NULL
\includegraphics{landscape-example_files/figure-latex/call-3.pdf} NULL
If these three calls would now be enclosed in a landscape environment, I would be happy and my problem would be solved.
The reason you are getting the simple markdown syntax for image insertion after including the landscape environment is because pandoc (the underlying document converter of r-markdown) does not parse the content of latex environments.
To add more details, when you click the knit button of Rstudio, the {knitr} package generates a markdown file containing the markdown syntax for image which as below,
\begin{landscape}
![](landscape-example_files/figure-latex/call-1.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-2.pdf)<!-- --> NULL
![](landscape-example_files/figure-latex/call-3.pdf)<!-- --> NULL
\end{landscape}
And then pandoc is supposed to convert the markdown syntax into latex commands (i.e. \includegraphics), But since pandoc sees the latex environment \begin{landscape}, it doesn't do the conversion and keeps them as is.
So to solve it, we can use the \landscape ... \endlandscape command instead of latex environment (thanks to the informative comment by #samcarter_is_at_topanswers.xyz)
---
title: "Landscape Problem"
author: "Dom42"
date: "`r Sys.Date()`"
output:
pdf_document:
keep_tex: yes
header-includes:
- \usepackage{pdflscape}
---
```{r function}
print.plots.landscape <- function() {
cat("\\landscape\n")
for (i in 1:3) {
temp.plot <- plot(hist(mtcars[,i]))
print(temp.plot)
}
cat("\n\\endlandscape\n")
}
```
```{r call, results='asis'}
print.plots.landscape()
```
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 use updated quarto and Rmarkdown and vtree ‘5.4.6’:
In the same project and same session:
Rmarkdown does what quarto does not:
Rmarkdown renders vtree(iris, "Species") and quarto not (allthough quarto renders inline)
What could be the problem for this?
See here a reproducible example:
1. Rmarkdown
---
title: "test"
author: "Me"
date: '2022-06-18'
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
```
## R Markdown
```{r cars}
vtree(iris, "Species")
```
2. Quarto
---
title: "Untitled"
format: html
editor: visual
---
## Quarto
```{r}
library(vtree)
vtree(iris, "Species")
```
When I click the Render button: -> it is NOT renderred:
When I render inline: -> it is renderred:
Quarto works a bit differently than R Markdown as it will run R only for the knitting process, and not for the conversion to output format, here HTML.
From the error message, vtree is writing to file the output in the R session temp folder. This folder is not persistent after the R session is closed, which happens once Quarto have run all the computation output. This means that the png file does not exists anymore when converting to HTML, hence the no image shown in HTML.
(regarding knitr warning, I believe it is knitr version matter, but that does not change the output).
Looking at vtree::vtree() function, it seems when knitting to HTML is detected R temp folder is used if none provided. IMO this should ne behave that way and it is an issue in vtree package.
To overcome the issue, you need to not let vtree do the default provide yourself a path. You can do that with folder argument. So this should work
---
title: "Untitled"
format: html
keep-md: true
---
## Quarto
```{r}
library(vtree)
if (!dir.exists("vtree_save")) dir.create("vtree_save")
vtree(iris, "Species", folder = "vtree_save")
```
I would report an issue in vtree repo about this behavior.
I am the author of the vtree package. I have just made a change to the code which I believe fixes the problem. See https://github.com/nbarrowman/vtree where there are instructions for downloading version 5.5.8 of the vtree package, which includes the fix.
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.
Accents in paragraphs work perfectly. Text in figures is correct in the plot viewer, but once I compile the pdf the accents disappear from the figures.
Here's an example that reproduces the issue.
---
title: 'Some title'
author: 'This be me'
date: '`r format(Sys.Date(), "%B %Y")`'
lang: es
header-includes:
- \usepackage{tikz}
output:
pdf_document:
fig_caption: yes
---
```{r global options, echo = F, message=F}
library(knitr)
opts_chunk$set(fig.width=6, fig.height=3.5, dev = 'tikz')
```
I have some paragraphs that include cool accents like áspid.
If I run the next chunk in the R console I see the accent on the figure it generated. But the accent is missing in the pdf.
```{r}
plot(pressure, main= "áspid")
```
This looks like a bug in the R tikzDevice package. It generates a .tikz file using the UTF-8 encoding, but doesn't include something like
\usepackage[utf8]{inputenc}
in it to declare the encoding. There are a number of references in its documentation to the "Unicode" section of the ?tikzDevice help topic, but there is no such section. You might want to report an issue on the Github page for the package, https://github.com/yihui/tikzDevice.
Edited to add:
After some experimentation, I can't see a way to add that line to the .tikz file, but requesting xelatex instead of the default LaTeX engine
does seem to work. You can do that by adding the R code
options(tikzDefaultEngine = "xetex")
into your early code chunk. That will use xelatex for the figures, pdflatex for the rest. ("xetex" is not a typo; that's how you request xelatex.)
If you want, you can switch to xelatex for the rest using latex_engine: xelatex in the YAML header, but the figures will still use pdflatex unless you also add the option setting.