Reputation: 517
Given the following rmarkdown
file:
```{r}
library(knitr)
```
```{r, out.width="100%"}
path <- "plotx.png"
knitr::include_graphics(path)
```
```{r, out.width="100%", out.height="150%"}
knitr::include_graphics(path)
```
There's no difference in size between the figures, as if the figure size options are not having any effect. Using other similar options, e.g. fig.width
, fig.height
, doesn't make any difference.
> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux bullseye/sid
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/atlas/libblas.so.3.10.3
LAPACK: /usr/lib/x86_64-linux-gnu/atlas/liblapack.so.3.10.3
locale:
[1] LC_CTYPE=en_CA.UTF-8 LC_NUMERIC=C LC_TIME=en_CA.UTF-8 LC_COLLATE=en_CA.UTF-8 LC_MONETARY=en_CA.UTF-8 LC_MESSAGES=en_CA.UTF-8
[7] LC_PAPER=en_CA.UTF-8 LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] knitr_1.29 slmisc_1.2.1 latticeExtra_0.6-29 lattice_0.20-41
loaded via a namespace (and not attached):
[1] png_0.1-7 mime_0.9 grid_4.0.2 magrittr_1.5 evaluate_0.14 highr_0.8 stringi_1.4.6 RColorBrewer_1.1-2 tools_4.0.2
[10] stringr_1.4.0 markdown_1.1 jpeg_0.1-8.1 xfun_0.16 yaml_2.2.1 compiler_4.0.2
Upvotes: 1
Views: 2340
Reputation: 9678
For HTML output, setting out.width="100%"
will scale the image to 100% width of its parent container, not 100% of the image pixels. Therby the aspect ratio is maintained, giving the largest possible result without distortion. Setting out.width="100%"
and out.height="150%"
thus produces the same result. Use pixels to get exact dimensions (this may result in distortion).
For LaTeX output, the aspect ratio is maintained, no matter if you use pixels or % (the only difference here is that pixels are treated as pixels and % are translated to scaling factors to \textheight
and \linewidth
). You may prevent this using the chunk option out.extra='keepaspectratio=false'
.
Example:
Image from here.
---
title: "Untitled"
output:
html_document: default
pdf_document: default
---
LaTeX and HTML: width = 100px, aspect ratio kept
```{r, out.width = "100px"}
tiger <- "tiger.png"
knitr::include_graphics(tiger)
```
LaTeX: aspect ratio kept, HTML: width = 700px, height = 200px aspect ratio not kept
```{r, out.height = "200px", out.width = "700px"}
knitr::include_graphics(tiger)
```
(LaTeX left, HTML right. Images are scaled to fit side-by-side.)
Upvotes: 6