您的问题与 knitr 无关,而是与光栅图像有关,光栅图像会产生白色边缘以防止其失真。例如,如果您键入 ? graphics::plot.raster,您将看到设置为 1 的 asp 参数保留来自栅格的比率。 在标准 R 输出中绘制您的图像,您将看到空白部分,如果您调整窗口,这些白色部分将被删除。所以你需要检查你的图像尺寸,然后在 knitr 中使用fig.asp 比率来生成一个框架,让你的图像适合。
检查您的图像比例
使用魔法的示例
url <- "https://cdn.pixabay.com/photo/2017/11/15/20/27/diamonds-2952447_960_720.png"
image<- image_read(url)
print(image)
返回
format width height colorspace filesize
1 PNG 960 600 sRGB 762423
你也可以使用 readPNG()
curl::curl_download(url, "image.png")
image <- png::readPNG("image.png",info=TRUE)
attr(image,"info")
来自 knitr options 我们有参数 fig.asp
fig.asp: (NULL; numeric) 绘图的纵横比,即比例
高度/宽度;当指定 fig.asp 时,绘图的高度(
块选项 fig.height) 由 fig.width * fig.asp 计算得到
所以这里我们计算height/width= 0.62。
使用 knitr 和 docx 输出
这里我使用作为opts.label 参数传递的方形输出设置在第一个块中,当图像很宽时,这会放大问题。
---
title: "Crop image ?"
output: word_document
---
```{r echo=FALSE}
require(knitr)
library(magick)
opts_template$set(squarefigure = list(fig.height = 6, fig.width = 6))
```
=lorem()
```{r opts.label ="squarefigure", echo=FALSE, fig.cap = "plot without setting the right raster output size"}
url <- "https://cdn.pixabay.com/photo/2017/11/15/20/27/diamonds-2952447_960_720.png"
img <- image_read(url)
img%>%grid.raster()
```
=lorem()
```{r opts.label ="squarefigure", fig.cap = "plot with correct margin, square size", fig.asp=0.62}
img%>%grid.raster()
```
=lorem()
如您所见,第一张图片有空白边缘,而第二张图片显示正确。
使用带有修剪的 LATEX
我知道问题中没有问到 LATEX 的答案,但如果有些读者
正在使用 knitr 或 sweave 来产生一个 LATEX 输出然后,以下
显示如何在 knitr 中修剪图像。使用的论据是
trim={<left> <lower> <right> <upper>,单位可以是 cm mm in ...(长度为 LATEX unit 之一)。要传递这些参数,您可以在块选项中使用 out.extra 参数。
请注意,像上面一样为您的图像使用 fig.asp 参数也可以。
\documentclass{article}
\usepackage{graphicx}
\usepackage[english]{babel}
\usepackage{blindtext}
\begin{document}
\blindtext
<<r1, echo=FALSE >>=
library(knitr)
library(ggplot2)
library(magick)
# download image to disk
url <- "https://cdn.pixabay.com/photo/2017/11/15/20/27/diamonds-2952447_960_720.png"
curl::curl_download(url, "image.png")
img <- image_read(png::readPNG("image.png"))
plot(img)
@
\blindtext
\newpage
\blindtext
<<r2, echo=FALSE,out.extra='trim={0 5cm 0 5cm},clip' >>=
plot(img)
@
\blindtext
\end{document}
使用 HTML
Here 是一个很好的博客,也可以用来理解 fig.retina 和 out.width 等论点
最后strip.white 参数是删除空行代码。它不会调整您的图像大小。
strip.white: (TRUE;logical) 是否去掉里面的白线
输出中源块的开头或结尾