Goal

Play with the options to show images in a RMarkdown document

Reference

This analysis is based on the blog post by ZevRoss link

Set-up

options(tidyverse.quiet = TRUE)
library(magick)
library(tidyverse)

Data

I will use the PNG image I created to view all named R colors, 657 in total, in GitHub and a plot generated with R package {ggplot2}

Image

im1 <- magick::image_read("all_R_named_colors_plot.png")
image_info(im1)
## # A tibble: 1 x 7
##   format width height colorspace matte filesize density
##   <chr>  <int>  <int> <chr>      <lgl>    <int> <chr>  
## 1 PNG     1200   1200 sRGB       FALSE   325697 38x38
knitr::include_graphics("all_R_named_colors_plot.png")

Note that, in the viewer pane, the image has better resolution than in the Rmarkdown doc. The reason is that once the doc in knitted, dpi is set to the default of knit (72) instead of the 96 dpi it had originally.

If we change dpi to 96 with dpi = 96 within function include_graphics, the results (pane and knitted doc) are the same

knitr::include_graphics("all_R_named_colors_plot.png", dpi = 96)

In the case of the plot, both images (Rmarkdown -pane- and knit) look like the same.

(plot1 <- ggplot(cars, aes(speed, dist)) + geom_point())

Using fig.width = 5 in the R chunk properties only changes figures and not images size

plot1

To change image size, we can use out.width given in % or px (pixels). The image is obtained with out.width = "30%" and the figure with out.width="200px"

knitr::include_graphics("all_R_named_colors_plot.png", dpi = 96)

plot1

Also, for images, we can use Markdown

![](all_R_named_colors_plot.png){width=50%}