Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 295
stevec Avatar asked May 06 '20 18:05

stevec


People also ask

How do you change the color of the title in ggplot2?

To change the color of X-axis label using ggplot2, we can use theme function that has axis. title. x argument which can be used for changing the color of the label values.

How do I center Ggtitle?

The default ggplot title alignment is not centered. It is on the left. It's possible to put the title in the middle of the chart by specifying the argument hjust = 0.5 in the function element_text() : p + theme(plot. title = element_text(hjust = 0.5)) .


1 Answers

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

like image 173
markus Avatar answered Oct 06 '22 01:10

markus