rggplot2phylogenyggsave

How do I save a phytools phenogram as an image?


I'm using the phenogram() function in the R package phytools to plot a phylogeny along axes of relative time (x) and phenotype, in this case mean annual temperature (y). It shows up in the plot window, but it doesn't seem to exist as a plot object that I can save externally as an image with ggsave.

Here is the main code and plot. I can provide a minimum reproducible example if necessary, but it's a lot of code, so I'm hoping this is perhaps a very easy and obvious thing to fix.

phenogram(tree_sub, bio01, colors = cols, fsize = 0.8, ftype = "i",
          xlab = ("Relative Time"), ylab = "Mean Annual Temperature (°C)",
          spread.labels = TRUE, spread.cost = c(1, 0))

ggsave(filename = "../output/APCT_phenogram_5Nov2021.png", plot = last_plot(), 
       width = 25, height = 16, units = "cm", dpi = 300)

Using plot = last_plot() saves instead a previous non-phenogram tree I had plotted using ggtree. Assigning my phenogram to an object called "tree_plot" and then calling that in ggsave produces the error:

Error: $ operator is invalid for atomic vectors

This seems to be because when I assign the phenogram to an object, it is only saving the x and y coordinates of each species in the tree (i.e. not the tree topology, branch lengths, axis labels, colors, etc.) Similarly, using png() doesn't work — it just produces a dotplot of points with the x and y coordinates listed in tree_plot.

tree_plot <- phenogram(tree_sub, bio01, colors = cols, fsize = 0.8, ftype = "i",
             xlab = ("Relative Time"), ylab = "Mean Annual Temperature (°C)",
             spread.labels = TRUE, spread.cost = c(1, 0))

png(filename = "../output/APCT_phenogram_5Nov2021.png",  width = 25, 
    height = 16, units = "cm", res = 300)

plot(tree_plot)

dev.off()

Does anyone know what kind of object R understands my phenogram to be when it's displaying the graph (shown below), and how I can save that, short of physically clicking through the export menu in RStudio?

this is what the plot that I'm trying to save looks like


Solution

  • If anyone comes across this, I figured it out with help from Dr. Revell, the creator of phytools. It turns out, having worked almost exclusively in ggplot2, I do not really know how to use png() properly!

    This is how it should go:

    png(filename = "../output/APCT_phenogram_5Nov2021.png",  width = 25, 
        height = 16, units = "cm", res = 300)
    
    phenogram(tree_sub, bio01, colors = cols, fsize = 0.8, ftype = "i",
              xlab = ("Relative Time"), ylab = "Mean Annual Temperature (°C)",
              spread.labels = TRUE, spread.cost = c(1, 0))
    
    dev.off()
    

    So make a sort of empty PNG, input all the info about it, then plot whatever you're trying to plot, and then turn off the graphics device.