【问题标题】:RMarkdown: ggplot into a tableRMarkdown:将ggplot放入表格
【发布时间】:2020-09-20 23:51:46
【问题描述】:

在 RMarkdown 中已经有一些考虑 ggplots 的问题,但没有人回答我的问题,即如何通过 knitr 将 ggplot 放入带有 kable() 的表中。 我试过这个链接:

How can I embed a plot within a RMarkdown table?

但到目前为止还没有运气。有什么想法吗?

这个想法是把所有的情节放到一个列表中

a<-list(p1,p2,p3...)

然后有桌子

{r}kable(a)

还应该能够包含其他文本

b<-("x","y","z",...)
kable (c(a,b),col.names=c())

感谢您的帮助

油炸锅

【问题讨论】:

  • 你能解释一下为什么你想要表格中的图也许使用子图和子标题就足够了,就像here解释的那样?
  • 不幸的是,这是要求。它需要采用表格的格式。我想替换手动创建 Word 文档以节省时间。

标签: r ggplot2 r-markdown knitr


【解决方案1】:

我对此进行了一些实验,以下是我能想到的最好的。这是一个完整的 Markdown 文档,您应该可以将其粘贴到 RStudio 中并点击 Knit 按钮。

这里有两个相关的说明。

  • 将文件链接直接设置为 kable 不起作用,因为它被包装在 html 中,因此它被解释为文本,因此我们需要将其 gsub() 它。另一种方法是设置 kable(..., escape = FALSE),但它是其他文本可能会导致问题的风险。
  • 此外,块选项 results = 'asis' 是使 print(kab) 返回原始 html 所必需的。

我不知道这些是不是实际应用的问题。

---
title: "Untitled"
author: "me"
date: "02/06/2020"
output: html_document
---

```{r, results = 'asis'}
library(ggplot2)
library(svglite)

n <- length(unique(iris$Species))
data <- split(iris, iris$Species)

# Create list of plots
plots <- lapply(data, function(df) {
  ggplot(df, aes(Sepal.Width, Sepal.Length)) +
    geom_point()
})

# Create temporary files
tmpfiles <- replicate(n, tempfile(fileext = ".svg"))

# Save plots as files, get HTML links
links <- mapply(function(plot, file) {
  # Suit exact dimensions to your needs
  ggsave(file, plot, device = "svg", width = 4, height = 3)
  paste0('<figure><img src="', file, '" style = "width:100%"></figure>')
}, plot = plots, file = tmpfiles)

# Table formatting
tab <- data.frame(name = names(plots), fig = paste0("dummy", LETTERS[seq_len(n)]))
kab <- knitr::kable(tab, "html")

# Substitute dummy column for figure links
for (i in seq_len(n)) {
  kab <- gsub(paste0("dummy", LETTERS[i]), links[i], kab, fixed = TRUE)
}
print(kab)
```

【讨论】:

    【解决方案2】:

    我已经按照我发布的链接中的说明找到了解决方法。

    我。将我的情节保存为图片 二、使用 sprintf() 使用 Rmarkdown 中的此命令将图片插入表中: ![](path/to/file)

    很糟糕,但它有效。如果有人找到解决方案,我将永远对智能编码感兴趣。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 2013-10-28
      • 1970-01-01
      • 2018-09-10
      • 2020-01-21
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多