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

Posted

技术标签:

【中文标题】ggplot / ggpubr:导出绘图时忽略annotate_figure【英文标题】:ggplot / ggpubr: annotate_figure ignored when exporting plot 【发布时间】:2019-04-03 15:26:55 【问题描述】:

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

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

示例: 见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"
)

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

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

【问题讨论】:

您是否将annotate_figure 的结果保存在任何地方?您应该将该结果传递给ggexport() 第二个@MrFlick 所说的——如果我保存annotate_figure 的输出并将that 传递给ggexport,它就可以工作。我清理了你的缩进,因为乍一看,这段代码看起来更多的是 ggarrange 的参数。我想知道您是否对此感到困惑,以为您将自己没有的东西分配给figure...? 【参考方案1】:

您只需将 annotate_figure(...) 分配给一个变量以显示或保存,如 cmets 中所述。

这里是它被分配回变量本身的答案:

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")

【讨论】:

以上是关于ggplot / ggpubr:导出绘图时忽略annotate_figure的主要内容,如果未能解决你的问题,请参考以下文章

如何在ggarrange ggpubr ggplot中调整边距(轴元素消失)R

R语言ggplot2可视化为组合图添加综合图例实战:使用ggpubr包ggarrange函数实现综合图例使用patchwork包实现综合图例

使用 ggpubr - R 标记每个图

ggplot2 ggsave 函数导致图形设备不显示绘图

for循环中的多个图忽略par

r语言ggbio包使用方法