我想主要将.Rmd文件导出为latex pdf。
这是我目前使用的代码
```{r ,fig.cap="caption",fig.env='figure', fig.width=10, fig.height=10,echo=FALSE, results='asis', warning=FALSE, strip.white=TRUE}
library(png)
library(grid)
img <- readPNG("filepath/overview.png")
grid.raster(img)
```
正如您所看到的,我已经在使用strip.white=TRUE
&amp; fig.env='figure'
但他们似乎无法工作。 .PNG文件在图像上方或下方没有任何(白色)间距。
我知道我可以直接使用乳胶并实现我想要的,但我希望能够在Word中重现这一点,如果需要的话。同样在Word中,图像上方和下方有半页空白空间。
非常感谢任何帮助。感谢
答案 0 :(得分:2)
您的问题与knitr无关,而是与光栅图像相关联,光栅图像会产生白边以防止其失真。例如,如果键入? graphics::plot.raster
,您将看到asp
参数设置为1,保留栅格的比率。 在标准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;数字)图的纵横比,即比率 高度/宽度;当指定fig.asp时,绘图的高度( chunk option fig.height)由fig.width * fig.asp
计算得出
所以我们在这里计算height/width
= 0.62。
这里我使用的是作为第一个块中设置的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的答案在问题中没有被问到,仍然是一些读者
然后使用knitr或sweave产生LATEX输出,如下
展示了如何在knitr中修剪图像。使用的论据是
trim={<left> <lower> <right> <upper>
,单位可以是厘米mm ...(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}
Here是一个出色的博客,也可用于理解fig.retina
和out.width
等参数
最后,strip.white
参数是删除空行代码。它不会调整您的图像大小。
strip.white :( TRUE; logical)是否删除中的白线 输出中的源块的开头或结尾