185

I have a local image that I would like to include in an .Rmd file which I will then knit and convert to HTML slides with Pandoc. Per this post, this will insert the local image :
![Image Title](path/to/your/image)

Is there a way to modify this code to also set the image size?

Community
  • 1
  • 1
Adam Smith
  • 2,584
  • 2
  • 20
  • 34
  • 5
    For finer control over sizes, you might end up having to use an [HTML img tag](http://www.htmlquick.com/reference/tags/img.html) – Marius Mar 25 '13 at 22:28
  • 5
    second @Marius's comment:http://daringfireball.net/projects/markdown/syntax says "As of this writing, Markdown has no syntax for specifying the dimensions of an image; if this is important to you, you can simply use regular HTML tags." – Ben Bolker Mar 25 '13 at 22:30
  • 12
    the problem using HTML tags is that the image is no longer recognized as an external resource by the Rmd conversion process, so it won't be included in a stand-alone version of the rendered HTML. – fabians Sep 29 '14 at 14:45

8 Answers8

226

The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:

Resizing local images

As of knitr 1.12, there is the function include_graphics. From ?include_graphics (emphasis mine):

The major advantage of using this function is that it is portable in the sense that it works for all document formats that knitr supports, so you do not need to think if you have to use, for example, LaTeX or Markdown syntax, to embed an external image. Chunk options related to graphics output that work for normal R plots also work for these images, such as out.width and out.height.

Example:

```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```

Advantages:

  • Over agastudy's answer: No need for external libraries or for re-rastering the image.
  • Over Shruti Kapoor's answer: No need to manually write HTML. Besides, the image is included in the self-contained version of the file.

Including generated images

To compose the path to a plot that is generated in a chunk (but not included), the chunk options opts_current$get("fig.path") (path to figure directory) as well as opts_current$get("label") (label of current chunk) may be useful. The following example uses fig.path to include the second of two images which were generated (but not displayed) in the first chunk:

```{r generate_figures, fig.show = "hide"}
library(knitr)
plot(1:10, col = "green")
plot(1:10, col = "red")
```

```{r}
include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path")))
```

The general pattern of figure paths is [fig.path]/[chunklabel]-[i].[ext], where chunklabel is the label of the chunk where the plot has been generated, i is the plot index (within this chunk) and ext is the file extension (by default png in RMarkdown documents).

Community
  • 1
  • 1
CL.
  • 14,577
  • 5
  • 46
  • 73
  • 22
    For pdf output, you will have to specify units for the figure dimensions, e.g. `out.width='100pt'`, otherwise latex will throw an error about illegal unit of measure. – andybega Apr 15 '16 at 11:23
  • 5
    Also works for MS Word output, but the out.width and out.height do not work – Ben May 23 '16 at 03:57
  • @andybega Thank you for your comment; I incorporated it into the answer. – CL. Sep 07 '16 at 16:49
  • 2
    you probably want `r, echo=FALSE, ...` – Jameson Quinn Feb 03 '17 at 21:20
  • This is strange: it works with ioslides Rmd, but not with Rmd to word or html. For the latter two, I get errors: pandoc: Could not fetch ~/Google Drive/SI/DataScience/UAC_JRI/output/Master_Report/SI_logo.png ~/Google Drive/SI/DataScience/UAC_JRI/output/Master_Report/SI_logo.png: openBinaryFile: does not exist (No such file or directory) – jzadra Jun 22 '17 at 23:50
  • 1
    @jzadra Please create a new question with reproducible code for your issue. At the moment I cannot reproduce your issue (copied the second code snippet verbatim to an RMD file and knitted to HTML and Word). – CL. Jun 23 '17 at 07:01
  • https://stackoverflow.com/questions/44728551/r-markdown-knit-fails-when-path-includes-for-html-pdf-document-but-works-for – jzadra Jun 23 '17 at 19:19
151

Un updated answer: in knitr 1.17 you can simply use

![Image Title](path/to/your/image){width=250px}

edit as per comment from @jsb

Note this works only without spaces, e.g. {width=250px} not {width = 250px}

tjebo
  • 21,977
  • 7
  • 58
  • 94
InspectorSands
  • 2,859
  • 1
  • 18
  • 33
111

You can also read the image using png package for example and plot it like a regular plot using grid.raster from the grid package.

```{r fig.width=1, fig.height=10,echo=FALSE}
library(png)
library(grid)
img <- readPNG("path/to/your/image")
 grid.raster(img)
```

With this method you have full control of the size of you image.

yoyoyoyosef
  • 7,000
  • 8
  • 40
  • 39
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • Thank you, this works using slidy. (Does not work as well with dzslides, but I don't believe it's an issue with the provided solution). – Adam Smith Mar 28 '13 at 19:07
  • 1
    Quotes around filepath are required in `img <- readPNG("path/to/your/image")` but I wasn't able to edit the solution. – Adam Smith Mar 28 '13 at 19:18
  • 1
    @AdamSmith I just copied your `path/to/your/image` from your question. Yes the path name is a string,, and you need quotes to define a string. Hope I am clear. – agstudy Mar 28 '13 at 19:48
  • 1
    By running this under RStudio, you will create a huge margin to the rendered png. – Paulo E. Cardoso Sep 29 '14 at 16:13
  • 22
    Future readers: This answer is [outdated](http://stackoverflow.com/a/36057971/2706569). – CL. Mar 17 '16 at 10:36
38

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

Ken Williams
  • 22,756
  • 10
  • 85
  • 147
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
21

If you are converting to HTML, you can set the size of the image using HTML syntax using:

  <img src="path/to/image" height="400px" width="300px" />

or whatever height and width you would want to give.

Shruti Kapoor
  • 1,106
  • 2
  • 12
  • 32
  • 7
    the problem with this solution is that the image is no longer recognized as an external resource by the Rmd conversion process, so it won't be included in a stand-alone version of the rendered HTML. – fabians Sep 29 '14 at 14:45
11

Had the same issue today and found another option with knitr 1.16 when knitting to PDF (which requires that you have pandoc installed):

![Image Title](path/to/your/image){width=70%}

This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:

![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}

You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.

Taylor Pellerin
  • 127
  • 1
  • 6
  • 2
    is this not exactly the same as my answer above? – InspectorSands Mar 29 '18 at 12:45
  • 3
    @hermestrismegistus nearly, but I am using percent of width rather than pixel width. I found this option to be useful because in my particular case I was putting multiple images side by side, which behaved better this way that when I gave exact width – Taylor Pellerin Mar 30 '18 at 17:15
8

Another option that worked for me is playing with the dpi option of knitr::include_graphics() like this:

```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```

... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.

Jan Alleman
  • 111
  • 1
  • 6
4

The knitr::include_graphics solution worked well for resizing the figures, but I was unable to figure out how to use it to produce side-by-side resized figures. I found this post useful for doing so.

Community
  • 1
  • 1
S.M.
  • 73
  • 1
  • 6