ggplot / ggpubr: annotate_figure ignored when exporting plot

Viewed 3214

I am trying to annotate a grid of plot that I arranged using ggarrange() from the ggpubr package. To do so, I use the annotate_figure() function after the plot was generated.

My problem: when doing it interactively (i.e. not creating files with my plot) it works perfectly, but when I export the files (using ggexport()), the annotations are not shown.

Example: see the example given in the documentation

data("ToothGrowth")
df <- ToothGrowth
df$dose <- as.factor(df$dose)

# Create some plots
# ::::::::::::::::::::::::::::::::::::::::::::::::::
# Box plot
bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco")
# Dot plot
dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco")
# Density plot
dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco")

# Arrange and annotate
# ::::::::::::::::::::::::::::::::::::::::::::::::::
figure <- ggarrange(bxp, dp, dens, ncol = 2, nrow = 2)
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
annotate_figure(figure,
    top = text_grob("Visualizing Tooth Growth", color = "red", face = "bold", size = 14),
    bottom = text_grob("Data source: \n ToothGrowth data set", color = "blue",
                       hjust = 1, x = 1, face = "italic", size = 10),
    left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90),
    right = "I'm done, thanks :-)!",
    fig.lab = "Figure 1", fig.lab.face = "bold"
)

This works perfectly. However, if I add ggexport(figure, "whatever.pdf"), the created file won't include the annotations.

Any idea how to solve this?

1 Answers

You just need to assign annotate_figure(...) to a variable to show or save as mentioned in the comments.

Here is the answer where it is assigned back the variable itself:

figure <- ggarrange(bxp, dp, dens, ncol = 2, nrow = 2)
figure <- annotate_figure(figure,
    top = text_grob("Visualizing Tooth Growth", color = "red", face = "bold", size = 14),
    bottom = text_grob("Data source: \n ToothGrowth data set", color = "blue",
                       hjust = 1, x = 1, face = "italic", size = 10),
    left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90),
    right = "I'm done, thanks :-)!",
    fig.lab = "Figure 1", fig.lab.face = "bold"
)
ggsave(filename="figure.png", plot = figure)
ggexport(figure, filename = "figure2.png")

arranged figure

Related