使用 ggplot_build 和 ggplot_gtable 后使用 ggsave 保存图形 [英] Saving a graph with ggsave after using ggplot_build and ggplot_gtable

查看:38
本文介绍了使用 ggplot_build 和 ggplot_gtable 后使用 ggsave 保存图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过更改 ggplot_build 生成的数据来修改使用 ggplot 构建的图形(原因类似于 在 geom_boxplot 中包含用于填充美学的缺失因子级别的空间).据我了解我在这个主题上找到的帮助,在对结果调用 ggsave 之前,我应该能够通过应用 ggplot_gtable 和arrangeGrob 来保存结果(将 grid.arrange() 绘图保存到文件).

I am modifying a graph built with ggplot by altering the data produced by ggplot_build (for a reason similar to Include space for missing factor level used in fill aesthetics in geom_boxplot). As far as I understand the help I found on this topic, I should be able to save the result by applying ggplot_gtable and arrangeGrob before calling ggsave on the results (Saving grid.arrange() plot to file).

但是我得到一个错误plot should be a ggplot2 plot",还有这个简单的可复制示例:

However I obtain an error "plot should be a ggplot2 plot", also with this simple reproductible example:

require('ggplot2')
require('gridExtra')
df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")), 
                  f2=factor(rbinom(100, 1, 0.45), label=c("young","old")),
                  boxthis=rnorm(100))
g <- ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot()
dd <- ggplot_build(g)

# Printing the graph works:
print(arrangeGrob(ggplot_gtable(dd)))

# Saving the graph doesn't:
ggsave('test.png',arrangeGrob(ggplot_gtable(dd)))

谁能解释为什么这不起作用?使用 ggplot_build() 修改数据后有没有办法使用 ggsave ?

Can anybody explain why this does not work ? Is there a way to use ggsave after modifying the data by using ggplot_build() ?

(我的软件包版本是 gridExtra_0.9.1 和 ggplot2_0.9.3.1)

(My version of the packages are gridExtra_0.9.1 and ggplot2_0.9.3.1)

推荐答案

它不起作用,因为 ggsave 想要一个 ggplot 类的对象,而你正在传递一个格罗布.arrangeGrob 有时会欺骗 ggsave 假装从 ggplot 继承,但前提是至少有一个 grob 属于这个类;然而,在这里,您只传递了一个 gtable.

it does not work because ggsave wants an object of class ggplot, while you're passing a grob. arrangeGrob will sometimes trick ggsave in pretending inheritance from ggplot, but only when at least one of the grobs belongs to this class; here, however, you're only passing a gtable.

也许最简单的解决方法是克隆 ggsave 并绕过类检查,

Perhaps the easiest workaround is to clone ggsave and bypass the class check,

ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2]

ggplot2 的开发版本不再需要这个 hack*,因为 ggsave 现在适用于任何grob.

The dev version of ggplot2 no longer requires this hack*, as ggsave now works with any grob.

*PS:这个 hack 不再起作用,因为arrangeGrob 现在返回一个 gtable,并且它的打印方法不在设备上绘制.

*PS: this hack works no longer, as arrangeGrob now returns a gtable, and its print method does not draw on a device.

这篇关于使用 ggplot_build 和 ggplot_gtable 后使用 ggsave 保存图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆