Brandon Bertelsen
Brandon Bertelsen

Reputation: 44708

Wrapping plots in another html container within an Rmd file

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?

Upvotes: 7

Views: 1122

Answers (1)

Ramnath
Ramnath

Reputation: 55735

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)
```

Upvotes: 6

Related Questions