【问题标题】:Programmatically insert header and plot in same code chunk with R markdown using results='asis'使用 results='asis' 以编程方式插入标题并使用 R markdown 在相同的代码块中绘图
【发布时间】:2017-09-30 19:34:52
【问题描述】:

Rmarkdown 中的results = 'asis' 块选项允许人们轻松地动态创建包含标题的文本。但是,我希望使用asis 选项动态创建一个标题,然后在同一个代码块中插入一些图形。

我能找到的最相关的答案在这里:Programmatically insert text, headers and lists with R markdown,但这个问题的答案不允许动态标题和这些动态标题中的图。

下面是一个简单的可重现示例,展示了我可以使用 results = 'asis' 实现什么和不可以实现什么

下面的代码符合我的预期,为每个物种创建了一个标头。

---
output: html_document
---
```{r echo = FALSE, results ='asis'}
for(Species in levels(iris$Species)){
  cat('#', Species, '\n')
}
```

下面的代码没有做我想要的。理想情况下,下面的代码将为每个 Species 生成一个标题,每个标题下方都有一个图。相反,它会在输出文件中生成单个 setosa 标头,然后是三个图。

---
output: html_document
---
```{r echo = FALSE, results ='asis'}
library(ggplot2)
for(Species in levels(iris$Species)){
  cat('#', Species, '\n')
  p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point()
  print(p)
}
```

有没有办法动态生成 3 个标题,每个标题下都有一个图?

【问题讨论】:

    标签: r plot ggplot2 knitr r-markdown


    【解决方案1】:

    您需要在绘图之后和标题之前添加一些新行,使用 cat('\n'):

    ```{r echo = FALSE, results ='asis'}
    library(ggplot2)
    for(Species in levels(iris$Species)){
      cat('\n#', Species, '\n')
      p <- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
        geom_point()
      print(p)
      cat('\n')
    }
    

    【讨论】:

    • 这似乎不适用于grid.draw。无论有多少\ncat,标题仍然会在情节之后打印,即使我在调用grid.draw之前在R代码中调用cat
    • 我遇到了你描述的同样的问题(而且这个答案被标记为正确答案的事实阻止了其他人试图解决这个问题)
    • 我设法让它在情节之后使用以下代码:cat('&lt;br&gt;') cat('\n') cat('\n')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 2019-03-08
    • 2021-10-18
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多