Tables and Figures side-by-side in Knitr or RMarkdown Beamer - r

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

Related

How to combine endfloat, markdown formatting and wordwrap in bookdown::pdf_document2 table

I am writing a Rmarkdown document using bookdown::pdf_document2 for which I have a table that needs to do several very specific things, but I simply cannot find the solution to get all of them to work at the same time:
The table needs to float to the end of the document as it would with the latex endfloat package.
The table elements have Markdown bold and italics formatting that should appear correctly in the final PDF document
One of the columns of the table has a lot of text that I would like to wrap within the table cell.
I have tried to get these three options to work with all sorts of combinations of knitr::kable, kableExtra::column_spec and pander, but I cannot find a way to get them all going at once. Below I am pasting an example Rmarkdown document with various tests, none of which fully works.
Is there a simple way to get the table to do what I want? Even a good workaround would be acceptable...
Thanks,
David
---
title: "Test table formatting"
author: "David M. Kaplan"
date: "5/24/2020"
output: bookdown::pdf_document2
header-includes:
- \usepackage[tablesfirst]{endfloat}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
```
# Data
```{r}
df.long = data.frame(
char = c('*this is some very long text with lots of words that will cause problems with word wrap if it is not properly handled with something like kableExtra*','**b**','~~c~~'),
num = c(1,2,3))
```
# Kable with format=pandoc
```{r}
knitr::kable(df.long,caption="test1",format="pandoc")
```
**Result:** Handles formatting, but table does not float and no wordwrap.
# Kable with booktab
```{r}
knitr::kable(df.long,caption="test2",booktab=TRUE)
```
**Result:** Floats, but does not handle formatting or do wordwrap.
# kableExtra for wordwrap
```{r}
knitr::kable(df.long,caption="test3",booktab=TRUE) %>%
kableExtra::column_spec(1,width="30em")
```
**Result:** Table floats and has wordwrap, but does not handle formatting.
# Pander
```{r}
pander::panderOptions("table.alignment.default","left")
pander::pander(df.long,caption="test4")
```
**Result:** Wordwrap and formatting, but does not float.
I found a solution to this problem. It basically consists of:
In the YAML header, add a header-includes entry declaring longtable to be a float flavor using some LaTeX magic I found here.
Use pander to format the table to get wordwrap
Specifically, I have the following in the YAML header:
header-includes:
- \usepackage[tablesfirst]{endfloat}
- \DeclareDelayedFloatFlavour*{longtable}{table}
and then the table can be generated with pander:
pander::panderOptions("table.alignment.default","left")
pander::pander(df.long,caption="test pander",split.cell=50)

Is there a way to add line breaks ONLY when exporting to PDF in R Markdown?

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

R Markdown tufte knitting gives "Error: pandoc document conversion failed with error 5"

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')
```

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

Inserting logo into beamer presentation using R Markdown

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).

Resources