Adding multiple figure captions in Rmarkdown

The following code chunk works. It is one of the many chunks in my RMD file (each demarcated by r{} )

I'm frustrated in adding figure captions for the two plots I created. Spent much time looking at discussions and have not made any progress. Such a caption is not needed for this assignment but I want to eventually use Rmarkdown to write papers. Thank you for your help.

Srini

library(dplyr)
library(ggplot2)

# 'pd_csvfile': population dynamics data  CSV file 
ComputeMeanAFSR <- function(pd_csvfile) {
  popdyn_df   <- read.csv(file=pd_csvfile, header=TRUE, as.is=TRUE)
  
  ## NEED AN AFSR VARIABLE in new COLUMN.  
  popdyn_df$AFSR <- popdyn_df$births/popdyn_df$py.women
  
  ## Return DF
  return(popdyn_df)
}

## CALL FUNCTIONS to Compute AFSR for UK, USA
## AFSR is saved as a new variable column in new CSV files
USA_AFSR  <- ComputeMeanAFSR("USA.csv")
UK_AFSR <- ComputeMeanAFSR("UK.csv")

## Plot AFSR Bar Charts for USA and UK
ggplot(data=USA_AFSR, aes(x=USA_AFSR$age, y=USA_AFSR$AFSR, fill=USA_AFSR$period)) + geom_bar(colour="black", stat="identity") + 
  labs(fill = "Period") + xlab("Age") + ylab("AFSR") + 
  ylim(0, 0.6) + ggtitle("AFSR for USA") + 
  theme(axis.text.x = element_text(size=12,angle=45,hjust=1,vjust=1))

ggplot(data=UK_AFSR, aes(x=UK_AFSR$age, y=UK_AFSR$AFSR, fill=UK_AFSR$period)) + geom_bar(colour="black", stat="identity") +
  labs(fill = "Period") + xlab("Age") + ylab("AFSR") + 
  ylim(0, 0.6) + ggtitle("AFSR for UK") + 
  theme(axis.text.x = element_text(size=12,angle=45,hjust=1,vjust=1))

Hi,

Welcome to the RStudio community!

If I get it correctly, all you want is to add a caption to individual figures right? In that case, there is an easy solution. Let's look at this example:

library(ggplot2)

ggplot(iris, aes(x = Petal.Length, y = Sepal.Length)) + 
  geom_point() + 
  labs(title = "Exploring Iris dataset",
       caption = "The graph shows two distict clusters of data") +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        plot.caption = element_text(hjust = 0, colour = "blue"))

image

As you can see, the plot contains a caption using the caption argument in the labs function. To center the text to the right and make it blue, I use the options in theme(plot.caption = element_text(...)). There are extra ways to mark-up the caption, but I think this will get you started.

I also found a nice post that provides a bit more info:

Hope this helps,
PJ

Thank you, PJ. I spent time looking for solution in RMD instead of ggplot2 as it'd be easy labeling and citing figures consistently in a report/paper. But your solution also works for me! I'm grateful.

Srini

Hi,

Could you tell me what you'd like a caption to be in markdown? Do you mean you'd like to be able to select the text in the PDF or word document instead of having it embedded in the picture?

PJ

Dear PJ:
I use LaTex to write papers. I include many figures with labels that I can cite in the body of the text.

RMD is like LaTex in some ways but it also does calculations inside. I have created multiple small chunks pf R-code (like the one I included) to do calculations and create plots. However, I don't know how to make RMD remember the plots outside each chunk so that I can refer to them within the RMD text body.

Your solution addresses an important part. Sorry, I was not clear in my earlier post (hope it is clearer now).

I appreciate your help

Srini

Did you look into the bookdown feature available for html_document too through bookdown::html_document2 format ?

Being able to reference plot and table in text is a feature included in bookdown. You should be able to add some caption thought fig.cap knitr chunk option

Is this not working for you ? could it be what you are looking for ?

2 Likes

I'm new to R and am slowly learning! Thank you for suggesting bookdown. I will look into it.

Srini

1 Like

This is a way to use R code outside the chunks in the markdown text

```{r setup, include=FALSE}
library(ggplot2)
```

# This is a title in markdown

```{r echo=FALSE}
figureNr = 1

ggplot(iris, aes(x = Petal.Length, y = Sepal.Length)) + 
  geom_point() + 
  labs(title = "This is the title in ggplot",
       caption = paste("Figure", figureNr, " - caption created within ggplot")) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        plot.caption = element_text(hjust = 0, colour = "blue"))

```

Figure `r figureNr` - caption created in markdown with variables from R

By using the back ticks and starting with r, you can then call the value of a variable to markdown like this: `r ...` or as in the example: `r figureNr` to display the value of the variable figureNr

Does this help?

PJ

Thanks, PJ. This will work!

Srini

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.