Search code examples
rggplot2png

How to save plots using ggMarginal?


ggsave() does not work as it treats the margins as transparent as shown in the following screenshot:

enter image description here

I tried doing png() and dev.off() but didn't have success. Is ggsave() not natively supported with the ggExtra package?

Question is straightforward. This text is me filling in whitespace to fulfill the character requirement.


Solution

  • Set the background colour for the backaground in ggsave explicitly:

    library(ggExtra)
    library(ggplot2)
    
    df <- data.frame(
      x =runif(100),
      y =rnorm(100)
    )
    
    
    p <- ggplot(df, aes(x = x, y = y)) +
      geom_point(color = "blue") +
      theme_minimal()
    
    print(p)
    
    p2 <- ggMarginal(p, 
                     type = "histogram", 
                     colour = "black", 
                     fill = "blue")
    
    print(p2)
    
    ggsave("test.png", 
           p2, 
           width = 8, height = 6, 
           units = "in",
           bg = "white")