With blogdown, you can include figures that result from R code like plots, as well as images from other sources in posts. For the former, you will need to be working from an R Markdown post, but for the latter, you can be working in either a markdown or R Markdown post. To read more about the differences between the two posting formats, read this chapter in the blogdown book.
Example 1: Including figures from R code
In an R Markdown post, you can insert an R code chunk that produces a figure like this:
library(ggplot2)
oplot <- ggplot(Orange, aes(x = age,
y = circumference,
colour = Tree)) +
geom_point() +
geom_line() +
guides(colour = FALSE) +
theme_bw()
oplot
You can use the knitr chunk options to control aspects of how the figure is displayed. Read more about these options in the bookdown book.
You may also use the chunk options to automatically produce numbered figures with captions. To do this, you will need to do two things:
- Label the R code chunk used to produce the figure
- Use the
fig.cap =
chunk option to provide a figure caption.
Note that the chunk label should not have underscores; it should only contain alphanumeric characters (a-z, A-Z, 0-9), slashes (/), or dashes (-).
To reference the figure in the text of your post, use the syntax \@ref(fig:chunk-label)
,1 where chunk-label
is the label of the chunk containing the R code that produces the figure.
```{r orange-tree-fig, fig.cap = "Growth of orange trees"}
oplot
```
Now, a reference in the text of the post to \@ref(fig:orange-tree-fig)
will produce a link to Figure 1.
Example 2: Including other images
You have a few options for adding other types of images to posts. First, you can use markdown syntax, as in:
![](/path/to/my/image.png)
In a blogdown site, this image file is assumed to be located in the /static/
directory. So if you save your image file in a subdirectory called /static/images/
, the file path would be (/images/image.png)
.
If you are working in an R Markdown post, you may also include images via the function knitr::include_graphics()
within an R code chunk. Again, blogdown assumes that the image file is in your /static/
directory, so the file path you provide should be relative to that directory. In the example below, the knit-logo.png file is located in the /static/images/
directory.
knitr::include_graphics(rep('/images/knit-logo.png', 3))
Figure 2 is an example of three knitr logos included in a figure environment. You can read more about the advantages of using the knitr::include_graphics()
function here.
Do not forget the leading backslash! And also note the parentheses
()
afterref
; they are not curly braces{}
.↩