【问题标题】:dynamic tabsets with multiple plots r markdown具有多个绘图的动态选项卡集 r markdown
【发布时间】:2018-11-23 09:55:17
【问题描述】:

我设法创建了一个基于项目列表创建动态选项卡集的 html 文档。添加一个情节在一个标签集上工作正常。现在如何在一个选项卡集上添加多个图?

这里是我开始的代码,但当您将文档编织到 html 输出时,它只显示每个选项卡集 1 个图。显然还缺少一些东西。

---
title: "R Notebook"
output:
  html_document:
    df_print: paged
editor_options:
  chunk_output_type: inline
---


### header 1
```{r}
library(ggplot2)
df <- mtcars

pl_list <- list()

pl1 <- qplot(cyl, disp, data = df[1:12,])
pl2 <- qplot(mpg, cyl, data = df[13:20,])
pl3 <- qplot(mpg, cyl, data = df[21:30,])
pl4 <- qplot(mpg, cyl, data = df[1:12,])

pl_list[[1]] <- list(pl1, pl3,  "one")
pl_list[[2]] <- list(pl2, pl4,  "two")
```


### header {.tabset}
```{r, results = 'asis', echo = FALSE}

for (i in seq_along(pl_list)){
  tmp <- pl_list[[i]]
  cat("####", tmp[[3]], " \n")
  print(tmp[1])
  cat(" \n\n")
  }
```

【问题讨论】:

    标签: r r-markdown knitr


    【解决方案1】:

    您可以进行一些改进。

    1. 使用文本和级别参数创建 cat 标头函数。

    使用它,您无需多次调用cat,它会自动创建想要的# 号码。

    catHeader <- function(text = "", level = 3) {
        cat(paste0("\n\n", 
                   paste(rep("#", level), collapse = ""), 
                   " ", text, "\n"))
    }
    
    1. print 使用lapply 绘图。

    完整代码如下所示:

    ---
    title: "R Notebook"
    output:
      html_document:
        df_print: paged
    editor_options:
      chunk_output_type: inline
    ---
    
    
    ```{r, functions}
    catHeader <- function(text = "", level = 3) {
        cat(paste0("\n\n", 
                   paste(rep("#", level), collapse = ""), 
                   " ", text, "\n"))
    }
    ```
    
    ### header 1
    
    ```{r}
    library(ggplot2)
    df <- mtcars
    
    pl_list <- list()
    
    pl1 <- qplot(cyl, disp, data = df[1:12,])
    pl2 <- qplot(mpg, cyl, data = df[13:20,])
    pl3 <- qplot(mpg, cyl, data = df[21:30,])
    pl4 <- qplot(mpg, cyl, data = df[1:12,])
    
    pl_list[[1]] <- list(pl1, pl3,  "one")
    pl_list[[2]] <- list(pl2, pl4,  "two")
    ```
    
    
    ## header {.tabset}
    
    ```{r, results = "asis", echo = FALSE}
    
    for(i in seq_along(pl_list)){
        tmp <- pl_list[[i]]
        # As you want to use tabset level here has to be lower than 
        # parent level (ie, parent is 2, so here you have to use 3)
        catHeader(tmp[[3]], 3)
        lapply(tmp[1:2], print)
    }
    ```
    

    【讨论】:

    • 您好,非常感谢您的宝贵时间和回复。它工作得很好,解决了我的问题!非常感谢!
    • @JLB 乐于助人!
    猜你喜欢
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2019-11-14
    • 2015-04-17
    • 1970-01-01
    • 2012-10-08
    • 2018-07-18
    相关资源
    最近更新 更多