How to set size for local image using knitr for markdown?

138,563

Solution 1

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.

Solution 2

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

Solution 3

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}

Solution 4

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.

Solution 5

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.

Share:
138,563

Related videos on Youtube

Adam Smith
Author by

Adam Smith

Updated on July 15, 2022

Comments

  • Adam Smith
    Adam Smith almost 2 years

    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?

    • Marius
      Marius about 11 years
      For finer control over sizes, you might end up having to use an HTML img tag
    • Ben Bolker
      Ben Bolker about 11 years
      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."
    • fabians
      fabians over 9 years
      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.
  • Adam Smith
    Adam Smith about 11 years
    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
    Adam Smith about 11 years
    Quotes around filepath are required in img <- readPNG("path/to/your/image") but I wasn't able to edit the solution.
  • agstudy
    agstudy about 11 years
    @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.
  • fabians
    fabians over 9 years
    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.
  • Paulo E. Cardoso
    Paulo E. Cardoso over 9 years
    By running this under RStudio, you will create a huge margin to the rendered png.
  • xhudik
    xhudik about 8 years
    this is a good solution but it can be used with html output only! The other output will ignore the setting
  • CL.
    CL. about 8 years
    Future readers: This answer is outdated.
  • andybega
    andybega about 8 years
    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.
  • Ben
    Ben almost 8 years
    Also works for MS Word output, but the out.width and out.height do not work
  • CL.
    CL. over 7 years
    @andybega Thank you for your comment; I incorporated it into the answer.
  • Jameson Quinn
    Jameson Quinn over 7 years
    you probably want r, echo=FALSE, ...
  • jzadra
    jzadra almost 7 years
    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.pn‌​g ~/Google Drive/SI/DataScience/UAC_JRI/output/Master_Report/SI_logo.pn‌​g: openBinaryFile: does not exist (No such file or directory)
  • CL.
    CL. almost 7 years
    @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).
  • jzadra
    jzadra almost 7 years
  • Dr. Mike
    Dr. Mike over 6 years
    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?
  • user101089
    user101089 over 6 years
    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?
  • Nick Kennedy
    Nick Kennedy over 6 years
    Try using % instead of px.
  • slhck
    slhck over 6 years
    Does not work for me either, on the latest version of all packages.
  • Samuel
    Samuel about 6 years
    Works for me using knitr 1.17. Make sure you write without spaces, e.g. {width=250px} not {width = 250px}.
  • warship
    warship about 6 years
    Works for me, easiest solution by far.
  • InspectorSands
    InspectorSands about 6 years
    is this not exactly the same as my answer above?
  • Taylor Pellerin
    Taylor Pellerin about 6 years
    @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
  • Lyngbakr
    Lyngbakr over 5 years
    This wouldn't work for me using xaringan with knitr_1.21.
  • André Costa
    André Costa about 5 years
    On ioslides this is not working yet, using knitr_1.21
  • dsz
    dsz almost 4 years
    For height AND width {height=640px width=480px} - a space between the two, not a comma or anything else.
  • giocomai
    giocomai almost 4 years
    with in percentage, e.g. {width=100%} works as well!