187

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?

3
  • 5
    For finer control over sizes, you might end up having to use an HTML img tag
    – Marius
    Commented Mar 25, 2013 at 22:28
  • 5
    second @Marius's comment: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 <img> tags."
    – Ben Bolker
    Commented Mar 25, 2013 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
    Commented Sep 29, 2014 at 14:45

8 Answers 8

229

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).

7
  • 23
    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
    Commented Apr 15, 2016 at 11:23
  • 5
    Also works for MS Word output, but the out.width and out.height do not work
    – Ben
    Commented May 23, 2016 at 3:57
  • @andybega Thank you for your comment; I incorporated it into the answer.
    – CL.
    Commented Sep 7, 2016 at 16:49
  • 2
    you probably want r, echo=FALSE, ... Commented Feb 3, 2017 at 21:20
  • 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.
    Commented Jun 23, 2017 at 7:01
155

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}

8
  • 6
    I tried this in knitr 1.16 and it didn't work when using ioslides. Has this feature then been removed or is it an ioslides issue?
    – Dr. Mike
    Commented Sep 3, 2017 at 13:26
  • 2
    Does not work for me either, on the latest version of all packages.
    – slhck
    Commented Sep 29, 2017 at 12:16
  • 6
    Works for me using knitr 1.17. Make sure you write without spaces, e.g. {width=250px} not {width = 250px}.
    – Samuel
    Commented Feb 19, 2018 at 17:42
  • 2
    Works for me, easiest solution by far.
    – warship
    Commented Mar 28, 2018 at 20:50
  • 5
    For height AND width {height=640px width=480px} - a space between the two, not a comma or anything else.
    – dsz
    Commented May 8, 2020 at 1:43
112

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.

5
  • 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
    Commented Mar 28, 2013 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
    Commented Mar 28, 2013 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
    Commented Mar 28, 2013 at 19:48
  • 1
    By running this under RStudio, you will create a huge margin to the rendered png. Commented Sep 29, 2014 at 16:13
  • 22
    Future readers: This answer is outdated.
    – CL.
    Commented Mar 17, 2016 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.

5
  • 2
    this is a good solution but it can be used with html output only! The other output will ignore the setting
    – xhudik
    Commented Feb 22, 2016 at 22:05
  • The <div> ... </div> solution seems very simple. What is the style setting to re-scale an image to a fixed percent, maintaining the aspect ratio?
    – user101089
    Commented Sep 19, 2017 at 0:52
  • Try using % instead of px. Commented Sep 19, 2017 at 6:21
  • Can the <div> ... </div> method be used inline with text? I want the image to side directly beside some regular text. Thx!
    – Cassandra
    Commented Oct 25, 2022 at 19:52
  • this can only be used with html content. I would recommend using knitr itself over this strategy
    – thus__
    Commented Mar 3, 2023 at 19: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.

1
  • 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
    Commented Sep 29, 2014 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.

2
  • 2
    is this not exactly the same as my answer above? Commented Mar 29, 2018 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 Commented Mar 30, 2018 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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.