Quarto Cross Reference references.bib in ggplot2

Hello,

I know how to reference figures in Quarto thanks to Quarto Subcaptions. For example, I can create subcaptions like figSubcap <- "Data Source: @X" and the cross reference works great when using the div syntax. However, when I pass figSubcap into a ggplot2 plot, it just passes the literal string Data Source: @X instead of Data Source: Reference (2020)... .

Question: Is there a way to get the citation generated in Quarto (like the Quarto Subcaption) and pass it to a ggplot2 plot, without manually creating the reference string?

Here's an example (not fully representative as it lacks a references.bib file). I pass the reference into the x-axis because when converting a ggplot2 plot to plotly via plotly::ggplotly, the ggplot2 caption is not carried forward. However, by putting the reference on the x-axis, we avoid adding an extra argument to plotly::ggplotly.

It really doesn't matter where I pass the reference; I just want to know if there's a syntax that allows the citation to be referenced in a ggplot2 plot.

library(ggplot2)

# Define the custom ggplot function
create_scatter_plot <- function(x_axis_label) {
  ggplot(mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    labs(x = x_axis_label, y = "Miles per Gallon (mpg)") +
    theme_minimal()
}

"@x" <- "Reference (2020)..."

quartoReference <- "@x"

# Example usage
plot <- create_scatter_plot(quartoReference)
print(plot)

Good evening,

I received a lot of assistance from Microsoft Copilot. The solution I have now works for my needs, but it isn't perfect because it doesn't extract only the last names of authors. Fortunately, my project mainly involves citing organizations like the CDC and Census Bureau. I did attempt to use bibtex::read.bib() , but I encountered issues with the author field. I suspect the problem might be due to user error or an incorrectly set up .bib file.

# Citation Generator (Value and Function (Not Perfect) --------------------
# This is required because rendering is different path than just running it in r
if (file.exists("./references.bib")) {
  bib_lines <- readLines("./references.bib") # Read the .bib file into a character vector
} else {
  bib_lines <- readLines("../references.bib") # Read the .bib file into a character vector
}


parse_bib <- function(bib_lines) { # Function to parse .bib entries
  entries <- list()  # Initialize an empty list to store entries
  current_entry <- NULL  # Variable to store the current entry being processed
  
  for (line in bib_lines) {  # Loop through each line in the .bib file
    if (grepl("^@", line)) {  # Check if the line starts with '@', indicating a new entry
      if (!is.null(current_entry)) {  # If there is a current entry being processed
        entries[[current_entry$key]] <- current_entry  # Add it to the entries list
      }
      current_entry <- list()  # Initialize a new entry
      current_entry$key <- sub("^@.*\\{([^,]+),", "\\1", line)  # Extract the entry key
    } else if (grepl("author", line)) {  # Check if the line contains 'author'
      authors <- sub(".*= \\{(.*)\\},", "\\1", line)  # Extract the authors
      current_entry$author <- strsplit(authors, " / ")[[1]]  # Split authors by '/'
    } else if (grepl("year", line)) {  # Check if the line contains 'year'
      year <- sub(".*= \\{(.*)\\},", "\\1", line)  # Extract the year
      current_entry$year <- year  # Add the year to the current entry
    }
  }
  
  if (!is.null(current_entry)) {  # Add the last entry to the list
    entries[[current_entry$key]] <- current_entry
  }
  
  return(entries)  # Return the list of entries
}

bib_entries <- parse_bib(bib_lines) # Parse the .bib file


generate_citation <- function(entry) { # Function to generate in-text citations
  # Remove curly braces and replace slashes with commas
  authors <- gsub("[{}]", "", entry$author)
  authors <- gsub("/", ",", authors)
  year <- entry$year
  citation <- paste(authors, " (", year, ")", sep = "")
  return(citation)
}

citations <- sapply(bib_entries, generate_citation) # Generate citations for all entries


for (entry in names(bib_entries)) { # Assign citations to variables based on keys
  assign(entry, citations[[entry]])
}

To reference a citation, all I have to do is type the variable name.
For a discussion on the same topic, click here to visit the Quarto forum.