How to display plot images in Rmarkdown through a for loop?

依然范特西╮ 提交于 2021-01-29 09:44:03

问题


I am handling a list of svg to print to a html document. I am using the magick package thought I am open to using other packages/solutions. The below code is my attempt to render my html document. However, instead of rendering the svg to the html file, it simply prints the metadeta into the document. Is there a way to overcome this behavior?

---
title: "My Test Report"
author: "Nicholas Hayden"
date: "6/12/2018"
output: html_document
---

```{r setup, set-options, include=FALSE, warning=FALSE}
library(rsvg)
library(magick)

paths <- c(
"~/path/to/my1.svg",
"~/path/to/my2.svg")

for (i in 1:length(paths)) {
  print(image_read_svg(paths[i]))
}
```

EDIT:

Some examples that elucidate the problem.

The Rmd command:

![]("~/path/to/my1.svg") fails and produces...

File "/Users/nicholashayden/Desktop/path/to/my1.svg" not found in resource path
Error: pandoc document conversion failed with error 99

As @mikeck pointed out. This may be a pathing issue. However, trying without the ~ produces the same error.


The html plain text of <img src="/Users/nicholashayden/path/to/my1.svg"> places the image in the html document while the ~ version fails with the same error as the previous.


The knitr::include_graphics() method produces whitespace with either the absolute path or the path with the ~



回答1:


I think you want to use include_graphics:

```{r}
for (i in 1:length(paths)) {
  print(knitr::include_graphics(paths[i]))
}
```



回答2:


I think I found a solution to this problem and its a bit of a pseudo-solution that gets the task completed but without explaining the underlying mechanism that generated the problem.

According to the knitr::include_graphics() documentation, the path argument is a A character vector of image paths - emphasis on vector. We can display the .svg files without magick and simply use, in references in the example, the below code.


# From example
paths <- c(
"/Users/nicholashayden/path/to/my1.svg",
"/Users/nicholashayden/path/to/my2.svg")

# Solution
knitr::include_graphics(paths)

This way we can avoid the use of the for loop that for some reason caused this problem. Though, this will not work with ~ in the path string. My issue was overlooking and assuming arguments in the knitr::include_graphics() function. Hopes this helps anyone in the future.



来源:https://stackoverflow.com/questions/50824040/how-to-display-plot-images-in-rmarkdown-through-a-for-loop

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