DEV Community

Andrew B. Collier
Andrew B. Collier

Posted on • Originally published at datawookie.dev on

{emayili} Styling Figures

{emayili} Styling Figures

By default <img> tags are wrapped in a tight <p></p> embrace by {knitr}. In general this works really well. However, I want to have more control over image formatting for {emayili}.

Adding a Hook

I’d like to have the <img> tags wrapped by <figure></figure>. It’d also be useful to have the option of inserting a <figcaption>. To support these requirements I added a {knitr} hook which adds in these tags. It responds to the following chunk parameters (all optional):

  • out.width — the figure width
  • fig.cap — figure caption
  • fig.alt — figure alternative text and
  • fig.class — class attached to the <figure> tag.

Example

First we’ll try out the figure caption with the following .Rmd file.

--------
output: html_document
--------

Enter fullscreen mode Exit fullscreen mode


{r fig.cap="Mercury Vapour"}
plot(pressure)

Enter fullscreen mode Exit fullscreen mode

Rendering this file, attaching to an envelope object and sending it with {emayili} yields the message below.

Nothing too exciting, just a caption neatly displayed below the plot.

Next let’s try attaching a class to the <figure> tag. We’ll use the CSS file figures.css. This file needs to be specified with the css_files argument to render().

body {
  margin: 30px 0px;
}

figure {
  margin-bottom: 20px;
}

figure.center {
  text-align: center;
}

figcaption {
  color: white;
  text-align: left;
  background-color: #9fa4a7;
  padding: 10px 20px;
}

figcaption::before {
  content: "Figure: ";
}
Enter fullscreen mode Exit fullscreen mode

In the .Rmd file we use the fig.class parameter to apply the center class to the <figure>.

--------
output: html_document
--------

Enter fullscreen mode Exit fullscreen mode


{r out.width="75%", fig.class="center"}
plot(pressure)

Enter fullscreen mode Exit fullscreen mode

And this is what the rendered message looks like.

The <img> is now centered in the <figure>.

Finally we’ll bring it all together by styling a figure caption.

--------
output: html_document
--------

Enter fullscreen mode Exit fullscreen mode


{r out.width="75%", fig.class="center", fig.cap="Mercury Vapour"}
plot(pressure)

Enter fullscreen mode Exit fullscreen mode

And the result in your inbox.

Since many automated reports use figures, the ability to style those figures should be very useful.





The {emayili} package is developed & supported by Fathom Data.

Top comments (0)