Question: Is there a way to use tikz notation within an Rmarkdown document without having to compile the document to a pdf?
And (sort of in the same direction):
Question: What is the best way to add mutiple tikz graphics in an RMarkdown document that I want to compile to html (while keeping the flexibilty to compile the file to pdf or word in a later stage as well)?
I've read many answers to posts (like TikZ in R Markdown or How can I use TikZ to make standalone (SVG) graphics?) that ask similar questions but I am still not completely sure, hence the questions.
I basically want to run this piece of code
---
output: pdf_document
header-includes:
- \usepackage{tikz}
---
## TikZ picture
Some picture
\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}
Instead of pdf_document I'd like to have html_document + some magic that automatically converts the tikz graphic to something that can be understood by html. Any suggestions?
I've just discovered that you can add tikz code in the code chunk of Rmarkdown when you modify the engine option :
---
output: html_document
---
Some picture
```{r,engine='tikz'}
\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}
```
The problem is that the figure is pixelized and the scale is not respected. One way to solve this may be to change the extension of the figure output (to pdf) and the width and the height with the chunk options (e.g. equals to 3 inches) :
```{r,engine='tikz',fig.ext='pdf',fig.width=3}
\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}
```
I'm sure there are better solutions but it's an easy way to use tikz code for an html output.
Related
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
I have quickly found this thread which resolves the issue on how to double space with the following code.
header-includes:
- \usepackage{setspace}\doublespacing
However, the double spacing also apply to code chunks which I would prefer them to be single space. I know I could add something like \singlespacing before and after the chunks, but since I use many chucks, is there a cleverer way?
It there a way to avoid the double spacing produced by \doublespacing in code chunks?
EDIT
Here is a reproducible example.
---
output: pdf_document
header-includes:
- \usepackage{setspace}\doublespacing
---
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```
Rmarkdown defines a Shaded environment, which is used to set these code snippets. You can patch it to automatically add \singlespace:
---
output:
pdf_document:
keep_tex: true
header-includes:
- \usepackage{setspace}\doublespacing
- \usepackage{etoolbox}
- \AtBeginEnvironment{Shaded}{\singlespace}
---
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```
I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
I think the question is quite self-explanatory but for avoidance of doubt I'll explain with more detail below:
I have an R Markdown document that works well if converted to HTML or uploaded to GitHub. When converting to PDF (using Latex), the results are not so pretty. I find that the biggest problem in a Latex PDF document are line breaks. I can fix the line breaks issue on the PDF document by adding "\ " characters, but that throws my HTML document out of whack too.
Is there a way to manually add line breaks (or "space before/after paragraphs") for the PDF output only?
Thank you!
You can redefine the relevant spacings in the YAML header. \parskip controls the paragraph spacing. Code blocks are shaded using a snugshade environment from the framed package. We can also redefine the shaded environment for code blocks to have some vertical space at the start. Here's a reproducible example. Note: I also added the keep_tex parameter so you can see exactly what the generated tex file looks like, in case this is useful:
title: "test"
author: "A.N. Other"
header-includes:
- \setlength{\parskip}{\baselineskip}
- \renewenvironment{Shaded}{\vspace{\parskip}\begin{snugshade}}{\end{snugshade}}
output:
pdf_document:
keep_tex: true
---
```{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.
Once you output to HTML, you can just print the HTML webpage as PDF. that might be an easy way keep the original format
I'd like to add a TikZ figure to a bookdown document in order to include some fancy graphics.
My primary output format is LaTeX which means that I could essentially just include the TikZ graphics verbatim in the Rmarkdown file and it would render fine. However, two problems are haunting me:
I'd like for the TikZ graphics to be part of a figure environment (for the numbering, caption etc).
I'd like to be able to render the same code to both PDF (LaTeX) and Gitbook (HTML).
Right now I have the following chunk which nicely produces the relevant graph as a figure when I render to pdf.
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext='pdf', fig.cap='Some caption.'}
\begin{tikzpicture}[scale=.7]
\draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
\draw [very thick] (5, 0) -- (13,0);
\node [below] at (2,-1) {\large Hello};
\node [below, align=center] at (0,-1) {\large Two\\ lines};
\end{tikzpicture}
```
However, there are two problems with the code:
I do not get any output when rendering to gitbook (using knitr and bookdown). I do get the figure caption, however, and if I render to html_document then it works too and I can see the graph.
For PDF the text is rendered using the computer modern font. I'd really like to change this, and the main font in the LaTeX document has already been set to something else. However, because the code is rendered locally by the TikZ engine and then inserted, it is not part of the full LaTeX document. Can I add some LaTeX options, packages etc. that are included by the TikZ engine before the code is rendered?
If there are other ways to include the TikZ code as part of a figure environment then I'd be happy to know.
Update: I guess the second point could be fixed by setting engine.opts = list(template = "latex/tikz2pdf.tex") where the necessary setup for LaTeX is included in the tikz2pdf.tex file. That file is read using LaTeX but I'd like to use xelatex to parse the file since I'm using the fontspec LaTex package. Can that be changed anyway?
I think I found an answer to both of my questions. It did take - as Yihui pointed out - quite some time. I'm including the answer here in case someone else turns out to need this (or myself at a later point).
Re 1) Render TikZ code to both pdf and gitbook
This turned out to be easier than I anticipated. Setting the argument fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png' as part of the chunk arguments helps this along. If I'm not knitting to PDF then imagemagick or some other software automatically converts it to PNG.
Re 2) Modifying the font
As listed in my updated question this can be set by tweaking the file tikz2pdf.tex that is part of knitr. A copy of it is included below so you don't have to search for it yourself. Setting the chunk argument engine.opts = list(template = "latex/tikz2pdf.tex") enables you to put any desired fonts, LaTeX packages etc in preamble before the TikZ code is rendered.
Looking through the knitr code, you can see that texi2dvi is used to parse the tikz2pdf.tex file with the TikZ code inserted. texi2dvi calls pdflatex which messes things up in case you need to use XeLaTeX or LuaLaTeX to include TrueType fonts using fontspec.
I'm sure it would be possible to fix that somehow in the texi2dvi code but a much simpler solution (at least for me) was to change the environment. If I set the two environmental variable before starting R and rendering the book then xelatex is automatically used for compiling all the code. In my bash terminal this is done using
export LATEX="xelatex"
export PDFLATEX="xelatex"
Voila!
The chunk becomes
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png', fig.cap='Some caption.', engine.opts = list(template = "latex/tikz2pdf.tex")
}
\begin{tikzpicture}[scale=.7]
\draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
\draw [very thick] (5, 0) -- (13,0);
\node [below] at (2,-1) {\large Hello};
\node [below, align=center] at (0,-1) {\large Two\\ lines};
\end{tikzpicture}
```
and tikz2pdf.tex is
\documentclass{article}
\include{preview}
\usepackage[pdftex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
%% INSERT YOUR OWN CODE HERE
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
I'm still surprised at the whole flexibility of knitr and related packages. Nice work Yihui!
I had problems compiling plots with The pgfplots and bookdown. Using engine='tikz', gave the error message: 'axis environment does not exist'. I fixed it by changing \usepackage{tikz} to \usepackage{pgfplots} in the tikz2pdf.tex file and using engine.opts = list(template ="Tikz2pdf.tex") as suggested.
I am trying to create a Beamer Presentation slide in RMarkdown / Knitr . In the slide I would like to have a table and a figure placed Side-by-side , and then some more text underneath. I can only get as far as my attempt as shown in the code. I would like to have the density plot placed, next to the Hmisc Table.
I am not using Kable or xtable since I get more control over the tables with Hmisc.
Also, How can I adjust the text characteristics (font-size, type, color) in the individual slides?
---
title: "BeamerTest1"
subtitle: Beamer Subtitle
author: "Author"
output:
beamer_presentation:
theme: CambridgeUS
colortheme: "beaver"
fonttheme: "structurebold"
---
## Slide with Table, Figure and Text
My topic for this slide
\scalebox{0.35}{
```{r hmisc-table, echo=FALSE, message=FALSE, results='asis'}
library(Hmisc)
latex(head(mtcars), file='', table.env=FALSE, center='none')
```
}
```{r, echo=FALSE, fig.show='hold', fig.height=1, fig.width=2.5}
library(ggplot2)
mt <- ggplot(mtcars, aes(mpg)) + geom_density(alpha=.2, fill="#FF6666") +
theme(axis.title.x = element_text(size=10),axis.text.x = element_text(size=8),
axis.title.y = element_text(size=10),axis.text.y = element_text(size=8))
mt
```
- Here is some Bullet Text
- And some more
- Subtext
- More Subtext
Thanks
As I've already answered the similar question like this, I repeat my answer in which I use ::: notation, adding the codes to create the output you may want.
You can use fenced_divs notation or ::: to create columns or `Two Content layout'. See also this page to know more about the notation.
## Slide With Image Left
::: columns
:::: column
left
::::
:::: column
right
```{r your-chunk-name, echo=FALSE, fig.cap="your-caption-name"}
knitr::include_graphics("your/figure/path/to/the-image.pdf")
#The figure will appear on the right side of the slide...
```
::::
:::
Since pandoc 2+, which supports the notation, was implemented in RStudio v1.2+, you may need to install RStudio v1.2+ first. The installation is easy enough (at least in my case); just download and install RStudio v1.2+. In the way of installation, the former version of RStudio on your computer will be replaced with the new one without uninstalling it manually.
The following figure is an example which you have if you implement the notation.
The MWE code which produced the slide above is here, too:
---
title: "BeamerTest1"
subtitle: Beamer Subtitle
author: "Author"
output:
beamer_presentation:
theme: CambridgeUS
colortheme: "beaver"
fonttheme: "structurebold"
---
## Slide with Table, Figure and Text
::: columns
:::: column
My topic for this slide
\scalebox{0.35}{
```{r hmisc-table, echo=FALSE, message=FALSE, results='asis'}
library(Hmisc)
latex(head(mtcars), file='', table.env=FALSE, center='none')
```
}
```{r, echo=FALSE, fig.show='hold', fig.height=1, fig.width=2.5}
library(ggplot2)
mt <- ggplot(mtcars, aes(mpg)) + geom_density(alpha=.2, fill="#FF6666") +
theme(axis.title.x = element_text(size=10),axis.text.x = element_text(size=8),
axis.title.y = element_text(size=10),axis.text.y = element_text(size=8))
mt
```
::::
:::: column
- Here is some Bullet Text
- And some more
- Subtext
- More Subtext
::::
:::
There have been issue having two column layout in beamer presentation. But in the same post there is workaround:
In short: Error is related to pandoc conversion engine, which treats everything between \begin{...} and \end{...} as TeX. It can be avoided by giving new definition for begin{column} and end{column} in yaml header.
Create mystyle.tex and write there:
\def\begincols{\begin{columns}}
\def\begincol{\begin{column}}
\def\endcol{\end{column}}
\def\endcols{\end{columns}}
In the Rmd file use these new definitions
---
output:
beamer_presentation:
includes:
in_header: mystyle.tex
---
Two Column Layout
-------
\begincols
\begincol{.48\textwidth}
This slide has two columns.
\endcol
\begincol{.48\textwidth}
```{r}
#No error here i can run any r code
plot(cars)
```
\endcol
\endcols
And you get:
Consider using a two column layout, like you would have to do if you were doing this directly in Beamer. See for example:
this question on doing this with the tools available with RStudio. (Please note that this is one area where RStudio and the RMarkdown package have evolved a lot recently and the question is somewhat dated, but it does hint at the features now available.)
this question for a solution with inline LaTeX and Pandoc. (This will also work with RStudio as the newer releases use a bundled copy of pandoc as the Markdown engine.)
this post on the pandoc mailing list discussing how to include Markdown inside of your LaTeX blocks, e.g. the Beamer commands/environments for columns.
this question on TeX Stack Exchange could help you, but you would need to adapt it a bit for RMarkdown (the question uses the Sweave-style syntax for embedding R into LaTeX with knitr).
The basic idea for your problem would be a two-column layout for the upper portion of the slide, and a one-column layout for the bottom. You then put the individual R code blocks into their own column. (You may need to play with vertical spacing if the two figures differ in size.)
The Rpres format is all-or-nothing on column layouts for a given slide (at least last time I checked), so that solution would be less than ideal when you want the bottom part of the slide to be a single 'column'.
Another solution would be combining the two figures into one and then displaying the merged figure. I'm not sure how you would do with a table and a graphic, but for two graphics, you could use the gridExtra package to place two lattice or ggplot2 (or even an unholy mixture of both) next to each other in a single grid and thus in a single, combined figure.
I think you want to set the chunk option fig.align=right as described here
I am trying to insert logo into beamer presenation using Rmarkdown, and it looks like size controls in \logo{\includegraphics[height=1cm,width=3cm]{logo.png}} do not work, no matter what values I put there, image is always of the same size. Any suggestions besides modifying image manually?
---
title: "Presentation"
author: "Author"
output:
beamer_presentation:
includes:
in_header: mystyle.tex
---
## R Markdown
This is an R Markdown presentation. 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.
## Slide with Bullets
- Bullet 1
- Bullet 2
- Bullet 3
## Slide with R Code and Output
```{r}
summary(cars)
```
## Slide with Plot
```{r, echo=FALSE}
plot(cars)
```
This is mystyle.tex
\logo{\includegraphics[height=1cm,width=3cm]{logo.png}}
\usetheme{Madrid}
\usefonttheme{serif}
\institute{Institute}
\setbeamertemplate{navigation symbols}{}
UPDATE: Quick work around - simply modifying image will not work - image is ugly and pixelated. Simply converting to pdf also didn't work well, so I used following R code to create pdf and use it in \logo{\includegraphics{logo.pdf}}
library(png)
library(grid)
img <- readPNG('logo.png')
img <- rasterGrob(img, interpolate=TRUE)
pdf(file = 'logo.pdf', width = 1, height = 0.25)
grid.newpage()
grid.raster(img)
dev.off()
I found solution; in beamer manual there is another way of using logo function and it works fine.
\pgfdeclareimage[height=0.2787cm, width=2.5cm]{logo}{logo.png}
\logo{\pgfuseimage{logo}}
I found this beamer tutorial quite useful. Just add the following to the file mystyle.tex passed to the YAML option in_header (as shown in the question):
\usepackage{tikz}
\titlegraphic {
\begin{tikzpicture}[overlay,remember picture]
\node[left=0.2cm] at (current page.30){
\includegraphics[width=3cm]{Beamer-Logo}
};
\end{tikzpicture}
}
and then you can play around with the node parameters to adjust the placement of your logo (Beamer-Logo).