0

以下命令集将打印一个格式适当的 pdf 文件,其中包含所表示的数据,Dimplot. 它运行正常,所有必需的包都可以正常加载。

project_name<-"my_project"
file_stem<-" my_dim_plot_"
fig_name<-paste0(figure_dir, "/", file_stem, project_name, ".pdf")
base_plot<-DimPlot(combined_data_obj, reduction = "tsne", label = TRUE) + NoLegend()
ggsave(fig_name, width = 20, height = 16, units = "cm", device='pdf')
base_plot
dev.off()

那么,为什么这段代码会打印一个空的 pdf?

save_ggplot_figure<-function(plot_object, figure_dir, file_stem, project_name) {
# Need to add functionality for mutiple plots, different file extensions, etc.
  fig_name<-paste0(figure_dir, "/", file_stem, project_name, ".pdf")
  ggsave(fig_name, width = 20, height = 16, units = "cm", device='pdf')
  plot_object
  dev.off()
}

project_name<-"my_project"; file_stem<-"tsne_dim_plot_"; project_name<-"my_project"
base_plot<-DimPlot(combined_data_obj, reduction = "tsne", label = TRUE) + NoLegend()
save_ggplot_figure(base_plot, figure_dir, file_stem, project_name)

我能看到的唯一区别是打印绘图然后转动的命令dev.off()在函数调用中,但这为什么重要呢?我尝试使用相同的代码pdf()代替ggsave(),但结果相同(它打印一个 4kb)空 pdf 文件,而不是在函数调用外部打印命令时打印的 120kb pdf 文件。

4

1 回答 1

0

您错误地使用了 ggsave,第一个参数应该始终是对象,然后您指定文件名。因此,您会得到一个空文件,因为ggsave()正在尝试在不存在的东西上创建 pdf。因此,如果您将功能更改为:

save_ggplot_figure<-function(plot_object, figure_dir, file_stem, project_name) {

  fig_name<-paste0(figure_dir, "/", file_stem, project_name, ".pdf")
  ggsave(plot_object, file = fig_name, 
  width = 20, height = 16, units = "cm", device='pdf')

}

这应该有效。你不需要打电话dev.off()

于 2021-03-13T11:05:01.287 回答