rggplot2gridextraggpubr

How can a title with subtitle be added with annotate_figure?


I am using ggarrange and annotate_figure to display two plots side-by-side. In my actual code, I have different titles on each subplot, but then need a common title and subtitle at the top of the entire plot.

I understand how to add text at the top, but how can I add two lines, each with different fonts (e.g. the top title should be large/bold, and the second line/subtitle should be smaller and regular font)?

Here is how I am producing the title. Is there a way to add a text_grob to the top?

library(tidyverse)
library(ggpubr)

df <- data.frame()
plot1 <- ggplot(df) + geom_point() + xlim(0, 10) + ylim(0, 100)
plot2 <- ggplot(df) + geom_point() + xlim(0, 10) + ylim(0, 100)

all.plots <- ggarrange(plot1, plot2)
annotate_figure(all.plots,
                top=text_grob("Antibiotic Effectiveness"))

Solution

  • You can use plotmath to create an expression for text_grob. See ?plotmath.

    library(tidyverse)
    library(ggpubr)
    
    df <- data.frame(x=runif(10,0,10), y=runif(10,0,100))
    plot1 <- ggplot(df) + geom_point(aes(x=x, y=y)) + xlim(0, 10) + ylim(0, 100)
    plot2 <- ggplot(df) + geom_point(aes(x=x, y=y)) + xlim(0, 10) + ylim(0, 100)
    
    all.plots <- ggarrange(plot1, plot2)
    # construct plotmath expression
    title <- expression(atop(bold("Figure 1:"), scriptstyle("This is the caption")))
    annotate_figure(all.plots,
                    top=text_grob(title))
    

    Created on 2019-10-02 by the reprex package (v0.3.0)