问题
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.
- First, we create a chunk hook to wrap chunk output inside a tag.
- We pass
wrap = div
as chunk option to wrap insidediv
. - Set
out.extra = ""
to foolknitr
into outputting html for plot output. Note that this is required only fordiv
tag and not forspan
, as markdown is parsed insidespan
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