r markdown word images with custom alt text

I am generating an accessible PDF using accessr. My question is about assigning a custom alt_text value for individual ggplots in a rmd document. This document will output a variable number for images first to an intermediate word document and finally to a PDF document (accessr performs the last translation).
The example markdown block looks like this:

{r popchart, echo = FALSE, fig.alt = 'Population Forecast Charts', fig.width=6, fig.align= 'center', results='asis'}
for(i in 2:length(chartsList[[2]][['plot']])) {
print(chartsList[[2]][['plot']][[i]])
}

The ggplot objects are stored in the chartList[[n]]['plot']] list.
The ggplots have an alt_text value assigned, so I can get the unique alt test string by using get_alt_text(). What I need to do is extract the unique alt text string for each ggplot chart and apply it to a code block (I think).

My question is how do I assign this alt text string to the code block? Do I have to create a unique code block for each ggplot? Any recommendations for doing this?

TIA

1 Like

I fashioned a solution to this task of creating custom alt text for r markdown chunks.
The basic idea is to create a general chunk and as many "sub-chunks" as charts. This uses templates and knit_expand to generate custom sub-chunks.

This may have some issues, so please send me any suggestions for improvements.
I'm curious about how to put this in a function within the RMD document.
Cheers--AB

```{r popchart, echo = FALSE, results='asis'}  # this is the "general chunk"
# The next command specifies the number of sub-chunks. "chartsList" is a list that contains pre-defined ggplot objects in the "plot" list.  
#The structure of the list is immaterial, you just need a list of ggplots.
  chNum <- length(chartsList[[2]][['plot']]  
 
 # Generate Alt Text List, pop_list has two columns,, one for the ggplot alt-text string
# the other for the ggplot
  pop_list <- list()
  for(i in chNum) {
    pop_list[[i]] <- c(ggplot2::get_alt_text(chartsList[[4]][['plot']][[i]]), chartsList[[2]][['plot']][[i]])
  }
#pop_src  contains the templated code for the sub-chunks  
# it has a specific name, e.g. "pop-1" and the other specific chunk options.
  pop_src <- list()
  for(a in 1:length(pop_list)){
    pop_src[[a]] <- knit_expand(
      text = c("```{r pop-{{a}}, echo=FALSE, fig.height=4.5, fig.width=6, fig.align= 'center', results='asis', fig.alt='{{b}}'}",
               "print(pop_list[[{{a}}]][[2]])",
               "```"
               ),
      a = a, b= unlist(pop_list[[a]][[1]]))
  }
# the last command "r knit(text..." is outside the general chunk and writes the ggplot and the custom alt-text to the document.

r knit(text = unlist(pop_src))