rggplot2

Change ggplot font size in middle of title


I would like to have more fine-grained control of the fonts in a ggplot title. Take the simple example below:

x <- c(0,1,2,3)
y <- c(0,1,4,9)
z <- data.frame(x,y)
ggplot(z,aes(x=x,y=y)) + geom_line()+ ggtitle("HELLO WORLD")

For this title, i.e. HELLO WORLD, I would like to change WORLD to a different font size and color than that of HELLO, while keeping it a single title line.


Solution

  • library(ggplot2)
    library(ggtext)
    
    z <- data.frame(x = c(0,1,2,3), y = c(0,1,4,9))
    
    ggplot(z, aes(x=x, y=y)) + 
      geom_line() + 
      ggtitle("Hello <i><b><span style='font-size:20pt; 
                                        color:#0072B2; 
                                        font-family:mono'>World</span></b></i>") +
      theme(plot.title = element_markdown())
    

    Created on 2024-07-10 with reprex v2.0.2