在Rmd文件中的另一个html容器中包装图 [英] Wrapping plots in another html container within an Rmd file

查看:115
本文介绍了在Rmd文件中的另一个html容器中包装图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,出于显示目的,我需要将输出的图包装在<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?

推荐答案

这是一种实现方法.

  1. 首先,我们创建一个块挂钩以将块输出包装在标签内.
  2. 我们将wrap = div作为块选项传递给包装在div内部.
  3. out.extra = ""设置为将knitr愚弄为输出html以进行图输出.请注意,这仅对于div标记是必需的,而对于span则不需要,因为markdown是在span标记内进行解析的.s
  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

完成!

这是要点,其中包含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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆