R markdown customize image size using png and grid.raster

I was working on an interesting article about APR using Rmarkdown in RStudio. I thought it would be more convincing to include some images. Then I realized the default syntax ![title](imagepath) might not be enough because the size might go crazy if you are not careful enough.

As you can see from this stackoverflow article, “markdown has no syntax for specifying the dimensions of an image”. Instead of writing your own html img tag, I prefer the solution of writing some R code to customize the size.

rmarkdownimagesize

As you can see, using library png and grid will easily read in your image and display that on the screen.

In your Rmarkdown code, simply specify the figure dimensions in the r tag will customize your image to whatever you want. 🙂

“`{r fig.width=2, fig.height=2}
library(png)
library(grid)
img <- readPNG(“images/apr1.png”)
grid.raster(img)
“`
“`{r fig.width=4, fig.height=4}
library(png)
library(grid)
img <- readPNG(“images/apr1.png”)
grid.raster(img)

“`

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s