首页 > 解决方案 > 带有ggplot和ggsave的R函数保存空文件

问题描述

我制作了一个绘制一些数据的函数,但我想加入“ggsave”。但是,当我第一次运行代码时,保存的文件是空的,没有数字。当我再次运行它时,第一次运行时制作的图形被保存等等。这显然不是我想要的,我认为这是因为 ggsave 发生在情节完成之前。由于 max.time 和 max.iter 需要很长时间,但在某些图中最多有 64 个点,而且很多点很接近,我不希望有太多重叠。另外,我对geom_label_repel 中一些论点的解释不是很了解,所以我尝试了一些东西,但也许我做了一些奇怪的事情。

我写的代码:

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 =""))
}

有没有人建议在情节完成之前解决我认为正在保存的这个问题?

我是一个相对缺乏经验的 R 用户,所以如果您有其他改进此代码的建议,请告诉我,但请善待 :)。

标签: rperformanceggplot2ggsave

解决方案


尝试将其保存在变量中并在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"))
}

推荐阅读