How to facet across tabs in ggplot2 / Rmarkdown?

2020-08-03 06:31发布

问题:

I am aware of facet_wrap and facet_grid for faceting. For more detailed graphics requiring more space, it could be useful to easily be able to facet across Rmarkdown tabs

Other than copying the graphic's code into each tab and filtering for the facet variable separately in each one, is there a native (ggplot2/Rmarkdown) way to do this?

To borrow the example from the linked question, the desired output would be to have the first facetted plot where it says 'tab content 1', and the second in the second tab, and so on (with as many tabs as facets)

回答1:

Here is how you could go about making these automated tabs

---
title: "Untitled"
author: "me"
date: "14 April 2020"
output: html_document
---

```{r}
library(ggplot2)
library(ggforce)
```

## A header {.tabset}

```{r, results='asis'}
n <- 10

# Make main plot
plot <- ggplot(diamonds) +
    geom_point(aes(carat, price), alpha = 0.1) 

# Facet_*_paginate loop over facets
plots <- lapply(seq_len(n), function(i) {
  plot + facet_wrap_paginate(~ cut:clarity, ncol = 1, nrow = 1, page = i)
})

# Print a tab and a plot for each n
# Important to set "results = 'asis'" in chunk options
for (i in seq_len(n)) {
  cat(paste0("\n\n### Tab ", i, "\n"))
  print(plots[[i]])
}
```