Emil
Emil

Reputation: 41

R function with ggplot and ggsave saves empty file

I made a function that plots some data but I wanted to incorporate 'ggsave'. However, when I run the code for the first time, the file that is saved is empty, there is no figure. When I run it again, the figure made during the first run is saved etc. This is obviously not what I want, and I think it is because ggsave takes place before the plot is finished. It takes a long time because of the max.time and max.iter but in some figures there are up to 64 points and many are close together and I don't want too much overlap. Also, I didn't really understand the explanations of some of the arguments in geom_label_repel, so I tried some things but maybe I did some weird things.

The code I wrote:

plot.frequency <- function(name, type, site){
  max_scale <- max(name$perc_spike, name$perc_reads)
  ggplot(name, aes(x= perc_spike, y = perc_reads, label=pattern)) +
    geom_point(color="blue", size = 1) +
    geom_abline(linetype = "dotted", slope = 1, intercept = 0)+
    labs(x = paste("Percentage of", tolower(type), "in spike"), y = paste("Percentage of", tolower(type), "as", tolower(site), "of read"),
         title = paste("Experiment ",Expnr, ". Frequency of ", tolower(type), " in spike vs at ", tolower(site), " of reads", sep = "")) +
    xlim(0, (max_scale)) + 
    ylim(0, (max_scale)) +
    geom_text_repel(data = subset(name),
                    aes(label=pattern),
                    size = 2.5,
                    box.padding = 0.20,
                    point.padding = 0.2,
                    segment.color = 'grey50',
                    direction = "both",
                    max.overlaps = 25,
                    max.time= 5,
                    max.iter = 1000000) +
    ggsave(filename = paste("/data/mydata/spike/figures/FiguresExp",Expnr,"/Exp",Expnr,"RelFreq",type,site,".png", sep =""))
}

Does anyone have a suggestion to solve this problem of what I think is saving before the plot is finished?

I'm a relatively unexperienced R user, so if you have other suggestions to improve this code please let me know, but please be kind :).

Upvotes: 0

Views: 1629

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

Try to save it in a variable and use it in ggsave.

plot.frequency <- function(name, type, site){
  max_scale <- max(name$perc_spike, name$perc_reads)
  ggplot(
    ##...code...for...ggplot
    ##...code...for...ggplot
    ) -> plt
  ggsave(plt, filename = paste0("/data/mydata/spike/figures/FiguresExp",
                Expnr,"/Exp",Expnr,"RelFreq",type,site,".png"))
}

Upvotes: 0

Related Questions