Search code examples
rggplot2dendrogramdendextendggsave

Saving dendrograms modified with dendextend in R


I want to rotate the order of several groups in a dendrogram and managed to do it with dendextend. However, when I try to save the plot with ggsave I end up with the original dendrogram, unrotated. Is there a way to save the rotated dendrogram with ggplot2? My code is as follows:

library(dendroextras)        
library(ggplot2)        
library(dendextend)        
d_copy_n <- colour_clusters(hc_test, k=6, groupLabels = as.roman)  
labels(d_copy_n)<-with(nl2[labels(d_copy_n)], Cell_type)   
d_copy_n <- set(d_copy_n, "labels_cex", 1)  
d_copy_n <- set(d_copy_n, "branches_lwd", 3)  
par(mar=c(0,2,0,0))  
d_copy_n %>%  
    rotate(121:86) %>%  
    plot()  
par(mar=c(0,2,0,0))      
ggsave("dendr_test.png", plot = plot(d_copy_n, cex.axis = 1, cex = 1), width = 21, height =7, units = "in", dpi = 300)
  

The plot I want will look like this: enter image description hererotared dendrogram



The plot I get looks like this: enter image description hereunrotated dendrogram


Solution

  • Several points:

    1. I don't think there is a need to use the dendroextras package. The dendextend package includes all the functions you need (with a more consistent API).
    2. No need for ggplot2 or ggsave, since the plot you're creating is not a ggplot2 plot, but rather an R base Graphics plot. Hence, you can save your plot using something like png("file_loc.png"); plotting_functions(); dev.off()
    3. You need to save the rotation into the dendrogram

    Like this:

    d_copy_n <- d_copy_n %>%  
        rotate(121:86)
    

    Now this part should work fine:

    ggsave("dendr_test.png", plot = plot(d_copy_n, ...
    

    Here's a simple example for what you've asked about without going through ggplot2 and dendroextras

    library(dendextend)        
    dend <- USArrests %>%
      dist() %>%
      hclust(method = "ave") %>%
      as.dendrogram()
    d_copy_n <- color_branches(dend, k=6)  
    d_copy_n <- set(d_copy_n, "labels_cex", 1)  
    d_copy_n <- set(d_copy_n, "branches_lwd", 3)  
    d_copy_n <- d_copy_n %>%  
      rotate(50:1)    
    
    # or just use:
    # d_copy_n <- color_branches(dend, k=6)  %>% 
    #          set("labels_cex", 1)  %>% 
    #          set("branches_lwd", 3)  %>% 
    #          rotate(50:1)  
    
    png("dend_plot.png")
    d_copy_n %>%  
      plot()  
    dev.off()
    

    enter image description here