knitr:如何在一起显示两个不同大小的图形?

12

我希望生成两张不同尺寸的图片,但是将它们并排展示。这个有可能吗?

这样做可以实现,但需要图片大小相同:


```{r two_plots_same_size_side_by_side, fig.width=5, fig.height=5}
    plot(...)
    plot(...)
```

这个不起作用,但它本来可以,因为在Markdown中,只需要一个换行符分隔的行会出现在同一行。

```{r normal_plot, fig.width=5, fig.height=5}
    plot(...)
```
```{r tall_plot, fig.width=5, fig.height=9}
    plot(...)
```
4个回答

9

一个选项是使用R命令制作一个宽度较大的图形,并将其提供给knitr处理,类似于:

```{r fig.width=10, fig.height=9}
layout( cbind( c(0,0,1,1,1,1,1,0,0), rep(2,9) ) )
plot(...)
plot(...)
```

9
如果你的输出是HTML格式的,另一种选择是使用out.extra=代码块选项,并在块中将它们设置为浮点对象。例如:
```{r fig.width=4, fig.height=6,echo=FALSE,out.extra='style="float:left"'}
plot(cars)
```{r fig.width=8, fig.height=6,echo=FALSE, out.extra='style="float:left"'}
plot(cars)
```

2
那很不错。如果有任何文本,我会在第二个图表后添加<div style="clear:both;"></div>。谢谢。 - nachocab
如果您有将原始HTML纳入的选项,最好将它们放在display:block;容器中。 - Brandon Bertelsen

9

另一个选项是使用向量作为out.widthout.height,如果您不介意调整图形大小,例如:

```{r out.width=c('500px', '300px'), fig.show='hold'}
boxplot(1:10)
plot(rnorm(10))
```

@nachocab你是否在使用最新版本的knitr? - Yihui Xie
你介意贴一下用Latex实现同样功能的代码吗?谢谢。 - dariaa
@dariaa 类似于 <<out.width=c('3in', '5in'), fig.show='hold'>>= 这样的东西。 - Yihui Xie
谢谢@Yihui。您能否看一下这个相关问题http://stackoverflow.com/questions/31992128/custom-layout-for-2-plots-using-knitr? - dariaa

7
你也可以使用gridExtra中的grid.arrange函数,它适用于grob或ggplot对象。
require(gridExtra)
pre_fig <- rasterGrob(readPNG("paper_figures/surf_0000.png"), interpolate=TRUE)
post_fig <- rasterGrob(readPNG("paper_figures/surf_0044.png"), interpolate=TRUE)
grid.arrange(pre_fig, post_fig, ncol=2)

也许我们应该先执行 install.packages(c("png","grid","gridExtra")) - upuil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接