I want to be able to add alt text to an automated officeR PowerPoint presentation. The plots are created using ggplot2. There is an ability to create alt text with ggplot2 using 'labs(alt="")', however I can only see this then is able to be used in Rmarkdown or Shiny but my project is already set-up in officer. Also there seems to be an ability to add alt_text to ph_with() but I cannot seem to make it work.
Reproduceable code is below:
library(ggplot2)
library(tidyverse)
library(officer)
# Create data
data = data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
plot=ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity") +
labs(alt="this is the test alt text")
# print alt text
get_alt_text(plot)
# produce ppt
doc <- read_pptx()
doc <- add_slide(doc, "Title and Content")
title <- fpar(ftext(paste0("Bar chart test")))
free_loc <- ph_location(left = 0.6, top = 0.2, width = 12, height = 1.5)
doc <- ph_with(doc, title, location = free_loc)
free_loc_body <- ph_location(left = 1.4, top = 1.8, width = 7, height = 5)
doc <- ph_with(doc, value = plot, location = free_loc_body, alt_text="test")
# save ppt
print(doc, target = "alt_example.pptx")
I had a look at the officer source code and this looks like a bug to me. I already filed an issue on GH.
In the meanwhile, a possible workaround would be to manually save the ggplot
using e.g. ggsave
. Then add it to your pptx using external_img
.
library(ggplot2)
library(officer)
# Create data
data <- data.frame(
name = c("A", "B", "C", "D", "E"),
value = c(3, 12, 5, 18, 45)
)
# Barplot
plot <- ggplot(data, aes(x = name, y = value)) +
geom_bar(stat = "identity") +
labs(alt = "this is the test alt text")
# produce ppt
doc <- read_pptx()
doc <- add_slide(doc, "Title and Content")
title <- fpar(ftext(paste0("Bar chart test")))
free_loc <- ph_location(left = 0.6, top = 0.2, width = 12, height = 1.5)
doc <- ph_with(doc, title, location = free_loc)
free_loc_body <- ph_location(left = 1.4, top = 1.8, width = 7, height = 5)
file <- tempfile(fileext = ".png")
ggsave(filename = file, plot = plot, width = 7, height = 5)
doc <- ph_with(doc,
value = external_img(file, alt = "test"),
location = free_loc_body
)
# save ppt
print(doc, target = "alt_example.pptx")