0

The following set of commands will print an appropriately formatted pdf file with the data represented, and this is the documentation for Dimplot. It runs appropriately and all the required packages load fine.

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()

Why, then, does this code print an empty 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)

The only difference I can see is that the commands to print the plot then turn dev.off() are inside a function call, but why should this matter? I tried the same code using pdf() instead of ggsave(), but with the same results (it prints a 4kb) empty pdf file instead of the 120kb pdf file printed when the commands are printed outside the function call.

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
  • use `print(plot_object)`. – r2evans Jun 04 '20 at 03:36
  • Please confirm that https://stackoverflow.com/q/26643852/3358272 resolved your problem, as I believe you're talking about a well-known "thing" with `ggplot2` plots. – r2evans Jun 04 '20 at 03:38
  • 2
    You shouldn't need to call `dev.off()` after using `ggsave`. But you may want to pass the actual `plot_object` to `ggsave`. – Marius Jun 04 '20 at 03:39

1 Answers1

0

You are using ggsave wrongly, the first argument should always be the object, then you specify the file name. Hence you get an empty file because ggsave() is trying to create a pdf on something that doesn't exist. So if you change the function to:

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')

}

This should work. and you don't need to call dev.off()

StupidWolf
  • 45,075
  • 17
  • 40
  • 72