geo_dd
geo_dd

Reputation: 313

Transparent background graph with ggplot2 in high resolution, R

I have a dataframe similar to the following example, and I want to combine two plots with the grid.arrange and then export them in high resolution and in transparent background. I get the plot in transparent the the resolution is terrible.

Any ideas how to do this?

I have seen some posts (post1,post2) but I need the plot to be in high resolution (about 600-800)

Thanks.

d <- iris
o1=ggplot(d, aes(x=d$Sepal.Length, y=d$Sepal.Width))+geom_smooth(method=lm,alpha=0.25,col='seagreen',lwd=0.1) +ylim(0,8)+xlim(0,8)+
    geom_point(shape=23,fill="black",size=0.2)+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                                                ,panel.grid.minor = element_blank()) +labs(x="bla bla",y="bla bla")+
    theme(axis.title.x = element_text(face="bold", size=8),axis.text.x = element_text(size=5))+
    theme(axis.title.y = element_text(face="bold", size=8),axis.text.y = element_text(size=5))+
    theme(plot.title = element_text(lineheight=.8, face="bold",size=8))+theme(
        panel.background = element_rect(fill = "transparent",colour = NA), 
        panel.grid.minor = element_blank(), 
        panel.grid.major = element_blank())
o2=ggplot(d, aes(x=d$Sepal.Length, y=d$Petal.Length))+geom_smooth(method=lm,alpha=0.25,col='seagreen',lwd=0.1) +ylim(0,8)+xlim(0,8)+
    geom_point(shape=23,fill="black",size=0.2)+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                                                ,panel.grid.minor = element_blank()) +labs(x="bla bla",y="bla bla")+
    theme(axis.title.x = element_text(face="bold", size=8),axis.text.x = element_text(size=5))+
    theme(axis.title.y = element_text(face="bold", size=8),axis.text.y = element_text(size=5))+
    theme(plot.title = element_text(lineheight=.8, face="bold",size=8))+theme(
        panel.background = element_rect(fill = "transparent",colour = NA), 
        panel.grid.minor = element_blank(), 
        panel.grid.major = element_blank())
png(bg = "transparent")
grid.arrange(o1,o2,ncol=1)
dev.copy(png,"graph.png",width=20,height=15,units="cm",res=800)
dev.off(dev.prev())
dev.off()

Upvotes: 1

Views: 8323

Answers (1)

Tung
Tung

Reputation: 28451

You need to specify the dimension and resolution in png. This works for me

png("graph.png", width=20, height=15, units="cm", res=800, bg="transparent")
    gridExtra::grid.arrange(o1, o2, ncol=1)
dev.off()

You can also use ggsave. Here I use cowplot::plot_grid to combind o1 & o2

o3 <- cowplot::plot_grid(o1, o2, nrow = 2)

ggsave(plot = o3, file = "graph2.png", 
       type = "cairo-png",  bg = "transparent",
       width = 20, height = 15, units = "cm", dpi = 800)

Upvotes: 3

Related Questions