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?
The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:
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 asout.width
andout.height
.
```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```
Advantages:
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).