Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: setting 'out.height' does suddenly not keep aspect ratio

Tags:

by using knitr::include_graphics with option out.height='50px' in a rmarkdown ioslides presentation the aspect ratio is not kept on my machine. Does anyone has an idea how to solve this problem?

Interestingly, this morning it worked. But not after I installed the R packages ggsn, ggmap, plotKML. Later I removed them, but the problem remains.

I use: Ubuntu 16.04.4, R version 3.4.4, current rmarkdown

Minimal example is:

---
title: "Untitled"
author: "Me"
date: "May 24, 2018"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo =T)
```

## R Markdown
setting out.height does NOT keep aspect ratio
```{r, out.height='50px', dpi=200}
   knitr::include_graphics("rect_circ.png")
```

setting out.width keeps aspect ratio
```{r, out.width='50px', dpi=200}
knitr::include_graphics("rect_circ.png")
```

output looks like this

like image 222
Robert Hering Avatar asked May 24 '18 14:05

Robert Hering


2 Answers

I guess you installed the png package by chance (it may be a dependency of the packages you mentioned). When png is available, include_graphics() will try to set the chunk option out.width to match your dpi setting. In your case, you set the out.height option, which leads to the problem of a distorted aspect ratio (the automatically calculated width is 96, and your manual height is 50).

If you have a desired figure size in the output, you may call

knitr::include_graphics("rect_circ.png", dpi = NA)

to avoid the automatic adjustment of out.width. If you have a desired DPI, you should leave out out.height, e.g.,

```{r}
knitr::include_graphics("rect_circ.png", dpi = 200)
``
like image 119
Yihui Xie Avatar answered Sep 28 '22 06:09

Yihui Xie


Within in my ioslides_presentation I created a row of jpg-graphics. For this to look nice I needed to set the out.height option, so that the pictures build a rectangular block. Usually this worked:

```{r, out.height="200px",dpi=200}
maps=c("map_1.jpg","map_2.jpg","map_3.jpg")
knitr::include_graphics(maps)
```

But with the png package installed the aspect ratio of the pictures was not kept. Applying the above mentioned changes, the chunk which workes looks like this:

```{r, out.height="200px"}
maps=c("map_anthroms_full.jpg","map_anthroms_rangelands.jpg")
knitr::include_graphics(maps, dpi=NA)
```

Note: Setting a resolution within include_graphics() or ```{r, ...} produces the same error.

like image 40
Robert Hering Avatar answered Sep 28 '22 05:09

Robert Hering