如何使用knitr为markdown设置本地图像的大小?

时间:2013-03-25 22:24:30

标签: image r markdown knitr pandoc

我有一个本地图片,我希望将其包含在.Rmd文件中,然后我knit并转换为Pandoc的HTML幻灯片。每this post,这将插入本地图像:
![Image Title](path/to/your/image)

有没有办法修改此代码以设置图像大小?

8 个答案:

答案 0 :(得分:158)

问题是陈旧的,但仍然受到很多关注。由于现有的答案已经过时,这里有一个更新的解决方案:

调整本地图像大小

knitr 1.12开始,有一个函数$scope.download = function(){ $window.open('/cv.pdf', '_blank'); }; 。来自include_graphics(强调我的):

  

使用此功能的主要优点是它可移植,因为它适用于?include_graphics支持的所有文档格式,因此您无需考虑是否必须使用,例如,LaTeX或Markdown语法,以嵌入外部图像。 与适用于普通R图的图形输出相关的块选项也适用于这些图像,例如knitrout.width

实施例

out.height

优点:

包括生成的图像

要构成在块中生成 (但未包含)的图的路径,块选项```{r, out.width = "400px"} knitr::include_graphics("path/to/image.png") ``` (图形目录的路径)以及{{1} (当前块的标签)可能很有用。以下示例使用opts_current$get("fig.path")包含在第一个块中生成(但未显示)的两个图像中的第二个:

opts_current$get("label")

图形路径的一般模式是fig.path,其中```{r generate_figures, fig.show = "hide"} library(knitr) plot(1:10, col = "green") plot(1:10, col = "red") ``` ```{r} include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path"))) ``` 是生成图的块的标签,[fig.path]/[chunklabel]-[i].[ext]是绘图索引(在此块中)和chunklabel是RMarkdown文档中的文件扩展名(默认为i)。

答案 1 :(得分:89)

您也可以使用png包阅读图片,并使用grid.raster包中的grid将其绘制为常规图。

```{r fig.width=1, fig.height=10,echo=FALSE}
library(png)
library(grid)
img <- readPNG("path/to/your/image")
 grid.raster(img)
```

使用此方法,您可以完全控制图像的大小。

答案 2 :(得分:62)

未更新的答案:在knitr 1.17中,您只需使用

即可
![Image Title](path/to/your/image){width=250px}

答案 3 :(得分:31)

这里有一些选项可以保持文件自包含而不会重新调整图像:

将图像包裹在div标记

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

使用样式表

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

如果您有多个图像,则可能需要为第二个选项使用nth-child伪选择器。

答案 4 :(得分:19)

如果要转换为HTML,则可以使用以下语法使用HTML语法设置图像的大小:

  <img src="path/to/image" height="400px" width="300px" />

或您想要给出的任何高度和宽度。

答案 5 :(得分:6)

今天遇到同样的问题,并在编织为PDF时要求$title = strip_tags($title); 另一个选项(要求你安装了pandoc):

knitr 1.16

此方法可能需要您进行一些试验和错误才能找到适合您的大小。它特别方便,因为它可以使两个图像并排放置更漂亮的过程。例如:

![Image Title](path/to/your/image){width=70%}

您可以获得创意并将其中的几个并排堆叠,并根据需要调整大小。有关更多提示和示例,请参阅https://rpubs.com/RatherBit/90926

答案 6 :(得分:4)

knitr :: include_graphics解决方案适用于调整数字的大小,但我无法弄清楚如何使用它来生成并排调整大小的数字。我发现this post对此非常有用。

答案 7 :(得分:2)

Another option that worked for me is playing with the dpi option of knitr::include_graphics() like this:

```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```

... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.