Wrapping plots in another html container within an Rmd file

你离开我真会死。 提交于 2021-01-27 04:36:07

问题


I have a situation where, for display purposes, I need to wrap an outputted plot in a <div> container.

At the most basic level, this is what I would like to do:

```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
plot(cars)
cat('</div>')
```

However, the output document looks like this:

![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-2.png)

Is there a workaround if you need to "wrap" output?

The same behaviour only seems to occur when it's wrapping the plot. Otherwise, including closed tags works as expected:

```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
cat('</div>')
plot(cars)
cat('<h1>Hello</h1>')
``` 

Yet wrapping the image seems to break it. I'm also noticing that <img> is wrapped in <p> is it possible to stop this behaviour?


回答1:


Here is one way to do it.

  1. First, we create a chunk hook to wrap chunk output inside a tag.
  2. We pass wrap = div as chunk option to wrap inside div.
  3. Set out.extra = "" to fool knitr into outputting html for plot output. Note that this is required only for div tag and not for span, as markdown is parsed inside span tag.s

DONE!

Here is a gist with Rmd, md and html files, and here is the html preview

## knitr Chunk Hook to Wrap

```{r setup, echo = F}
knit_hooks$set(wrap = function(before, options, envir){
  if (before){
    paste0('<', options$wrap, '>')
  } else {
    paste0('</', options$wrap, '>')
  }
})
```


```{r comment = NA, echo = F, wrap = 'div', out.extra=""}
plot(mtcars$mpg, mtcars$wt)
```


来源:https://stackoverflow.com/questions/15370291/wrapping-plots-in-another-html-container-within-an-rmd-file

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