ggplot / ggpubr:导出绘图时忽略 annotate_figure

Gal*_*ose 3 r ggplot2 gridextra ggpubr

ggarrange()我正在尝试注释我使用包中安排的绘图网格ggpubr。为此,我annotate_figure()在生成绘图后使用该函数。

我的问题:当以交互方式进行操作时(即不使用我的绘图创建文件),它工作得很好,但是当我导出文件(使用ggexport())时,注释不会显示。

示例: 参见文档中给出的示例

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"
)
Run Code Online (Sandbox Code Playgroud)

这非常有效。但是,如果我添加ggexport(figure, "whatever.pdf"),创建的文件将不包含注释。

知道如何解决这个问题吗?

ykp*_*mre 5

您只需将 annotate_figure(...) 分配给一个变量即可按注释中所述显示或保存。

这是将其分配回变量本身的答案:

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")
Run Code Online (Sandbox Code Playgroud)

排列图