How to facet across tabs in ggplot2 / Rmarkdown?

被刻印的时光 ゝ 提交于 2020-07-06 05:27:20

问题


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]])
}
```


来源:https://stackoverflow.com/questions/61207158/how-to-facet-across-tabs-in-ggplot2-rmarkdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!