This tutorial describes how to label exhibits in your Markdown file. We will caption tables, figures, and images. This tutorial shows quick-and-dirty methods. Download the Markdown file used to generate this post here.

Tables

Imagine I want to convert this data frame named “table.raw” to a polished table in a report that I am generating using Markdown.

table.raw
##            city  pop
## 1      New York 22.6
## 2   Los Angeles 18.7
## 3       Chicago  9.8
## 4          D.C.  9.8
## 5 San Francisco  9.6

Were I to generate the table using the kable() command from the knitr package, I could implement the caption using the command option caption. You can format the table using kableExtra package (click here for tips on formatting kable() tables). I will add the caption “Major Metro Area Populations”:

library(knitr)                                                     #Load packages
library(kableExtra)
kable(table.raw,                                                   #Specify object presented in table
      col.names = c("City", "Pop."),                               #Setting column labels
      caption = "Table 1: Major Metro Area Populations") %>%       #Table caption inserted here,
                                                                   #Pipe at end of line to invoke next line:
  kable_styling(bootstrap_options = "striped", full_width = F)     #Additional formatting options
Table 1: Major Metro Area Populations
City Pop.
New York 22.6
Los Angeles 18.7
Chicago 9.8
D.C. 9.8
San Francisco 9.6

Figures

I use “table.raw” data to generate a figure using the package ggplot2. Note that I use the reorder() operation when defining the x-axis, in order to sort cities by population size rather than alphabetical order.:

To caption figures, you can set figure captions through the fig.cap option when you set your Markdown chunk.

``{r, echo = T, warning = F, fig.cap = "Major Metro Area Populations (in M)"}
library(ggplot2)
ggplot(table.raw, aes(x = reorder(city, -pop), y = pop)) + geom_bar(stat = 'identity')

Figure 1: Major Metro Area Populations (in M)

Images

Captioning images is easy for a basic image insertion. There are other methods, which allow for finer adjustments (e.g., click here).1. Note that you enter this command in the main body of a Markdown file, not in a chunk.

![Figure 2: Nice pic, even better caption!](Picture.jpg)

Figure 2: Nice pic, even better caption!


  1. Photo credit: By Michal Klajban – Own work, CC BY-SA 4.0, https://commons.wikimedia.org/w/index.php?curid=80189727

Leave a Reply

Your email address will not be published. Required fields are marked *