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?
Here is one way to do it.
wrap = div
as chunk option to wrap inside div
.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.sDONE!
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)
```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With