Side by Side Code and Plot

plot pull

Show code and plot on same slide without copy-paste

Emil Hvitfeldt true
05-22-2021

If you want to show your code AND plots you can use the .pull-left[] and .pull-right[] content classes. To avoid copy-paste of the code you can use some knitr magic to have the code shown in one place and have the results rendered another place.

Code first

When you are doing code first you set the following options in the code chunk chunkname, fig.show="hide" and put

where you want the figure to appear. The chunkname must match.

Plot first

The previous approach does not work if you want the plot to appear before the text. To make this work you need to set the following chunk options

Note, if you want to do this multiple times in a slide deck you need to specify a different chunkname for each pair of chunks.

Result

Rmd

---
output:
  xaringan::moon_reader:
    css: ["default"]
    lib_dir: libs
    seal: FALSE
    nature:
      ratio: "16:9"
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

# Side by Side: code first

.pull-left[
```{r code-first, fig.show="hide", warning=FALSE}
library(ggplot2)
library(palmerpenguins)
colors <- c("darkorange", "purple", "cyan4")

ggplot(penguins) +
  aes(bill_length_mm, bill_depth_mm,
      color = species) +
  geom_point() +
  theme_minimal() +
  scale_color_manual(values = colors) +
  labs(title = "Bill depth and length")
```
]

.pull-right[
```{r, echo=FALSE}
knitr::include_graphics(
  knitr::fig_chunk("code-first", "png")
)
```
]

---

# Side by Side: plot first

.pull-left[
```{r ref.label="plot-first", echo=FALSE, warning=FALSE}
```
]

.pull-right[
```{r plot-first, fig.show="hide", warning=FALSE}
library(ggplot2)
library(palmerpenguins)
colors <- c("darkorange", "purple", "cyan4")

ggplot(penguins) +
  aes(bill_length_mm, flipper_length_mm,
      color = species) +
  geom_point() +
  theme_minimal() +
  scale_color_manual(values = colors) +
  labs(title = "Bill and Flitter lengths")
```
]

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Hvitfeldt (2021, May 22). Xaringan Gallery: Side by Side Code and Plot. Retrieved from https://xaringan.gallery/examples/side-by-side-code-plot/

BibTeX citation

@misc{hvitfeldt2021side,
  author = {Hvitfeldt, Emil},
  title = {Xaringan Gallery: Side by Side Code and Plot},
  url = {https://xaringan.gallery/examples/side-by-side-code-plot/},
  year = {2021}
}