Inline HTML styling in ggplot2 ggtitle

Hi all,

I have an R Markdown document that I've been rendering to Word as part of a weekly report for a few years now. I just updated packages and now a ggtitle with some inline HTML styling is rendering as plain text.

Here is a simpler example of what I am trying to do:
(EDIT to add that I had been using ggtext also)

library(tidyverse)
library(ggtext)

a_number <- 1024

ggplot(mtcars, aes(mpg, wt, colour = cyl)) + 
  geom_point() +
  theme(plot.title = element_markdown()) +
  ggtitle(paste0("This is my red number: ", 
                 "<span style=color:'#e15759'>",
                 a_number,
                 "</span>."))

So what would be the current correct way to apply styling to individual parts within a ggtitle?

> packageVersion('ggplot2')
[1] ‘3.4.0’
> packageVersion('ggtext')
[1] ‘0.1.2’

This package does the job:

My mistake, I went back to my original and realized I had also been using ggtext already, I just didn't include it in this example. I've edited to add that part in.

Having done so now the closing '</span>' tag disappears, but still not the right behavior. Really odd.

Does the problem only occur when exporting to Word? Have you tried in html for example? If you just run the chunk without compiling the document, is the title rendered correctly in the preview?

I get the same result rendering Word, HTML, the chunk by itself, or just the standalone piece of code above. Same result in all contexts.

Yes, I just tried and the problem is present.


EDIT: change the position of ' to solve: style='color:#e15759' instead of style=color:'#e15759'

Yes, that appears to be it. Somehow the other syntax was okay before but now this is the way it needs to be. Fixes my original code as well.

Thank you!

EDIT: Also works without any quotes, like <span style=color:#e15759>. Not sure where I got the idea that I needed them in the first place.

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.