[英]Saving a graph with ggsave after using ggplot_build and ggplot_gtable
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 ).我正在通过更改 ggplot_build 生成的数据来修改使用 ggplot 构建的图形(原因类似于在 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 ).
据我了解我在这个主题上找到的帮助,在对结果调用 ggsave 之前,我应该能够通过应用 ggplot_gtable 和arrangeGrob 来保存结果(将grid.arrange() 绘图保存到文件)。
However I obtain an error "plot should be a ggplot2 plot", also with this simple reproductible example:但是我得到一个错误“情节应该是一个ggplot2情节”,还有这个简单的可复制示例:
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)))
Can anybody explain why this does not work ?任何人都可以解释为什么这不起作用? Is there a way to use ggsave after modifying the data by using ggplot_build() ?
有没有办法在使用 ggplot_build() 修改数据后使用 ggsave ?
(My version of the packages are gridExtra_0.9.1 and ggplot2_0.9.3.1) (我的软件包版本是 gridExtra_0.9.1 和 ggplot2_0.9.3.1)
it does not work because ggsave
wants an object of class ggplot
, while you're passing a grob.这是行不通的,因为
ggsave
希望类的对象ggplot
,当你路过一个GROB。 arrangeGrob
will sometimes trick ggsave
in pretending inheritance from ggplot
, but only when at least one of the grobs belongs to this class;有时,
arrangeGrob
会欺骗ggsave
假装从ggplot
继承,但ggplot
是至少有一个 grobs 属于这个类; here, however, you're only passing a gtable
.然而,在这里,您只传递了一个
gtable
。
Perhaps the easiest workaround is to clone ggsave and bypass the class check,也许最简单的解决方法是克隆 ggsave 并绕过类检查,
ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2]
Edit: The dev version of ggplot2 no longer requires this hack*, as ggsave
now works with any grob .编辑: ggplot2 的开发版本不再需要这个 hack*,因为
ggsave
现在适用于任何 grob 。
*PS: this hack works no longer, as arrangeGrob now returns a gtable, and its print method does not draw on a device. *PS:这个 hack 不再起作用,因为arrangeGrob 现在返回一个 gtable,并且它的打印方法不在设备上绘制。
A work around is to plot the gtable object with grid.draw() and then use dev.copy() to transfer the plot to a file.解决方法是使用 grid.draw() 绘制 gtable 对象,然后使用 dev.copy() 将绘图传输到文件。
Remember to use also dev.off() just afterward.记住之后还要使用 dev.off() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.