12.5 Output figures in the HTML5 format

By default, plots in R Markdown are included in the tag <img src="..." /> in a <p> or <div> tag in the HTML output. This example below shows how to use the HTML5 <figure> tag to display plots.

  1. ---
  2. title: Output figures in `<figure>` tags
  3. output: html_document
  4. ---
  5. Given a plot file path `x` and a figure caption in the chunk
  6. option `options$fig.cap`, we want to write the plot in the
  7. HTML5 tag in this form:
  8. ```html
  9. <figure>
  10. <img src="PATH" alt="CAPTION" />
  11. <figcaption>CAPTION</figcaption>
  12. </figure>
  13. ```
  14. Now we redefine the `plot` hook (only when the output format
  15. is HTML):
  16. ```{r}
  17. if (knitr::is_html_output()) knitr::knit_hooks$set(
  18. plot = function(x, options) {
  19. cap <- options$fig.cap # figure caption
  20. tags <- htmltools::tags
  21. as.character(tags$figure(
  22. tags$img(src = x, alt = cap),
  23. tags$figcaption(cap)
  24. ))
  25. }
  26. )
  27. ```
  28. The plot from the code chunk below will be placed in the
  29. `<figure>` tag:
  30. ```{r, fig.cap='A scatterplot for the cars data.'}
  31. par(mar = c(4.5, 4.5, .2, .2))
  32. plot(cars, pch = 19, col = 'red')
  33. ```
  34. We add some CSS styles to "see" the `<figure>` and
  35. `<figcaption>` tags better (the `figure` has a dashed
  36. border, and the caption has a light pink background):
  37. ```{css, echo=FALSE}
  38. figure {
  39. border: 2px dashed red;
  40. margin: 1em 0;
  41. }
  42. figcaption {
  43. padding: .5em;
  44. background: lightpink;
  45. font-size: 1.3em;
  46. font-variant: small-caps;
  47. }
  48. ```

The figure output is shown in Figure 12.2. Note that we actually overrode the default plot hook in this example, while most other examples in this chapter build custom hooks on top of the default hooks. You should completely override default hooks only when you are sure you want to ignore some built-in features of the default hooks. For example, the plot hook function in this case did not consider possible chunk options like out.width = '100%' or fig.show = 'animate'.

A figure in the HTML5 figure tag.

FIGURE 12.2: A figure in the HTML5 figure tag.

This example shows you what you can possibly do with the plot file path x in the plot hook. If all you need is to customize the style of figures, you do not have to use the HTML5 tags. Usually the default plot hook will output images in the HTML code like this:

  1. <div class="figure">
  2. <img src="PATH" />
  3. <p class="caption">CAPTION</p>
  4. </div>

So you can just define css rules for div.figure and p.caption.