Swapnil Potdar
Swapnil Potdar

Reputation: 41

R ggsave save thumbnail size (200 x 200),scaled image

I am trying to plot some simple x,y line plots with the data in a loop. Code would generate hundreds of such plots and the idea is to save these plots in a thumbnail size image (something like 200 x 200 pixels, DPI wont matter) and embed it in Excel file along with the data. When I plot through ggplot2 it looks perfectly fine but when I want to save it, I get either cropped image showing only part of image or a very narrow plot with mismatched sizes of labels/texts. If I put the scale as 2 then it looks correct but would not fit my criteria.

My data frame looks like this.

Drug=c("A","A","A","A","A","A")
Con=c(10,100,1000,10,100,1000)
Treatment=c("Dox","Dox","Dox","Pac","Pac","Pac")
Value=c(-3.8,-4.5,-14.1,4,-4.6,3.5)
mat_tbl=data.frame(Drug,Con,Treatment,Value)

p=ggplot(data=mat_tbl,aes(x=Con,y=Value,colour=Treatment,group=Treatment))+geom_point(size =      4)+geom_line()+labs(title="Drug A",x="Concentration",y="Value") +    scale_y_continuous(limits=c(-25,125),breaks=seq(-25,125,by=25)) + theme_bw()
ggsave(filename = "curve_drug.png",plot=p,width=2,height=2,units="in",scale=1)

Any suggestions about which parameters I need to work on?

Upvotes: 4

Views: 6992

Answers (1)

MS Berends
MS Berends

Reputation: 5239

Please take a look at the function that I wrote to do this, as a helper function for ggsave:

plot.save <- function(plot, 
                       width = 800, 
                       height = 500, 
                       text.factor = 1, 
                       filename = paste0(
                                    format(
                                      Sys.time(), 
                                      format = '%Y%m%d-%H%M%S'), '-Rplot.png'
                                    )
                                  ) {

    dpi <- text.factor * 100
    width.calc <- width / dpi
    height.calc <- height / dpi

    ggsave(filename = filename,
                 dpi = dpi,
                 width = width.calc,
                 height = height.calc,
                 units = 'in',
                 plot = plot)
}

As you can see, the DPI is nothing more than a text factor for plots in R.

Consider this:

plot.save(some_ggplot, width = 400, height = 400, text.factor = 1)

pic1

And this (changed text.factor from 1 to 0.5):

plot.save(some_ggplot, width = 400, height = 400, text.factor = 0.5)

pic2

Both pictures are exactly 400 x 400 pixels, just like I set in the function.


Also maybe interesting: the first parameter of plot.save is the actual ggplot. So now I made the following possible (using the dplyr package), which I use a lot:

ggplot(...) %>%
  plot.save(200, 200) # here I've set width and height in pixels

Upvotes: 6

Related Questions