Corrupted font spacing from ggplot2 in either qmd output or ggsave

When both printing and saving a ggplot2 plot I'm finding that the first I call works correctly but that second always gets what appears to be corrupted spacing. If I restart R then print and save in the opposite order, the first called is again ok, but the second bad.

Not sure what I'm doing wrong here. Can anyone help?

Example:

Sample code:


title: "Untitled"
format: html
editor: visual


library(ggplot2)
library(glue)
library(ggtext)
library(showtext)
 

sysfonts::font_add_google("Roboto slab", "title")
sysfonts::font_add_google("Montserrat", "body")

showtext::showtext_opts(dpi = 300)
showtext::showtext_auto(enable = TRUE)
 

span = function( color, text ) {
  glue( "<span style = 'color:{color};'>{text}</span>" )
}


lineColour = "gray80" 

plot =
  ggplot( ) + 
  labs(
    x = "Days",
    y = "Change",
    title = glue("Change of  prices"),
    subtitle = glue( "{span(lineColour, 'Individual price timelines')}, ",
    ), 
  ) +
  
  scale_x_continuous( breaks = c(0, c(7, 14, 28)) ) +
  scale_y_continuous( labels = scales::percent,
                      breaks = seq(-1.0, 10, 0.25), 
  ) +
  
  ggthemes::theme_tufte(base_family = "body") +
  theme(
    plot.subtitle = element_markdown(
      size = 24, lineheight = 0.6, padding = margin(0, 0, 10, 0),  
    ),
    text =       element_text(family = "body", size = 20),
    plot.title.position = "plot",
    plot.title = element_text( family = "title",
                               size = 36,
                               margin = margin(b = 10), 
    ), 
  ) 

# Whichever of the following is called first is ok, the other corrupted: 

plot
ggsave( "test-null3.png", plot  )
# plot
 

Hi,

I am not sure, but I suspect this is related with the use of the span function. Do you get the same difference if you set your subtitle to 'Individual price timelines' and define the color in the call to theme ( plot.subtitle = ... ) ?

Many thanks for the idea but, regrettably, removing the span doesn't fix the error.