Cropping charts in another html container in Rmd file

I have a situation where, for display purposes, I need to crop the displayed chart in the <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 is as follows:

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

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

The same behavior occurs when it completes the plot. Otherwise, including private tags, it works as expected:

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

But the wrapper of the image seems to break it. I also notice that <img> wrapped in <p> can this behavior be stopped?

+6
source share
1 answer

Here is one way to do it.

  • First, we create a piece of the fragment to display the fragment inside the tag.
  • We pass wrap = div as a chunk parameter for wrapping inside a div .
  • Set out.extra = "" to trick knitr into html output for graph output. Note that this is only required for the div tag, not the span , as markup is parsed inside the span .s tag

DONE!

Here is a gist with Rmd, md and html files, and here is a 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) ``` 
+5
source

All Articles