Search code examples
rggplot2patchworkggtext

Colour in title of patchwork of ggplots using ggtext?


How can a patchwork of ggplots be given a colourful title using ggtext?

Example

Suppose we have four plots

library(ggplot2)
library(patchwork)
library(ggtext)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

p4 <- ggplot(mtcars) + 
  geom_bar(aes(gear)) + 
  facet_wrap(~cyl) + 
  ggtitle('Plot 4')

These can be arranged like so

patch <- (p1 + p2) / (p3 + p4)
patch

enter image description here

The patchwork can be given a title like so

patch +
  plot_annotation(
  title = "Here is a regular title")

enter image description here

A single ggplot can be given a colourful title like so

p1 +
  ggtitle("Here <span style='color:#953011;'><strong>is a colourful title</strong></span>") +
  theme(plot.title = element_markdown(lineheight = 1.1)) 

enter image description here

How can the patchwork of ggplots be given a colourful title. Here's my unsuccessful attempt

patch +
  plot_annotation(
  title = "Here<span style='color:#953011;'><strong>is a colourful title</strong></span>") +
  theme(plot.title = element_markdown(lineheight = 1.1)) 

enter image description here


Solution

  • plot_annotation has a theme argument, so you can do

    #remotes::install_github("wilkelab/ggtext")
    library(ggplot2)
    library(patchwork)
    library(ggtext)
    
    patch <- (p1 + p2)
    
    patch +
      plot_annotation(
        title = "Here <span style='color:#953011;'><strong>is a colourful title</strong></span>",
        theme = theme(plot.title = element_markdown(lineheight = 1.1)))
    

    enter image description here