在Rmd文件中的另一个html容器中包装图 [英] Wrapping plots in another html container within an Rmd file
问题描述
我有一种情况,出于显示目的,我需要将输出的图包装在<div>
容器中.
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>')
```
但是包装图像似乎破坏了图像.我还注意到<img>
被包裹在<p>
中,是否可以停止这种行为?
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?
推荐答案
这是一种实现方法.
- 首先,我们创建一个块挂钩以将块输出包装在标签内.
- 我们将
wrap = div
作为块选项传递给包装在div
内部. - 将
out.extra = ""
设置为将knitr
愚弄为输出html以进行图输出.请注意,这仅对于div
标记是必需的,而对于span
则不需要,因为markdown是在span
标记内进行解析的.s
- 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
完成!
这是要点,其中包含Rmd,md和html文件,这是 html预览 >
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)
```
这篇关于在Rmd文件中的另一个html容器中包装图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!