Saving a graph with ggsave after using ggplot_build and ggplot_gtable

前端 未结 2 1901
清歌不尽
清歌不尽 2020-11-29 07:09

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 aesthetic

相关标签:
2条回答
  • 2020-11-29 07:33

    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.

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

    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.

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

    0 讨论(0)
  • 2020-11-29 07:33

    A work around is to plot the gtable object with grid.draw() and then use dev.copy() to transfer the plot to a file.

    Remember to use also dev.off() just afterward.

    0 讨论(0)
提交回复
热议问题