Search code examples
rggplot2ggpubr

Prpoblem in ggsave() with ggscatterhist()


I have am annoying problem with the ggsave() function of the package ggplot2 by doing scatterhist() diagrams with packahe ggpubr.

Below the example:

library(ggplot2)
library(ggpubr)


Graph1 <- ggscatterhist(
 iris, x = "Sepal.Length", y = "Sepal.Width",
 color = "Species", size = 3, alpha = 0.6,
 palette = c("#00AFBB", "#E7B800", "#FC4E07"),
 margin.params = list(fill = "Species", color = "black", size = 0.2)
)

Here the problem, I try to save the graph and:

ggsave(plot=Graph1, filename="Grafico1.png", device="png", dpi=500)

Error in UseMethod("grid.draw") : 
  no applicable method for 'grid.draw' applied to an object of class "c('ggscatterhist', 'list')"

In this way, removing the plot definition it works fine, but I am not feeling comfortable with this. Is this perhap a bug?

ggsave(filename="Grafico1.png", device="png", dpi=500)

Solution

  • If we address to documentation it says:

    an object of class ggscatterhist, which is list of ggplots, including the following elements:...

    So Graph1 is not a ggplot object but list of three ggplot objects: Graph1$sp:

    enter image description here

    Graph1$xplot:

    enter image description here

    and Graph1$yplot:

    enter image description here

    So you can't reliably use ggplot object specific functions like ggsave for ggscatterhist objects without without thorough investigation into their nature. Answering your question if it is a bug I would answer no. ggsave(filename="Grafico1.png", device="png", dpi=500) is working without any erros as it is saving current graphic device that contains plot outputs of all ggscatterhist list elements.

    Should you decide to use other graphic devices try Cairo package as well:

    library(Cairo)
    
    Cairo(600, 600, file="Grafico1.png", type="png", bg="white")
    Graph1 
    dev.off()
    

    The above listed code will reliably give you the desired Grafico1.png file.