简体   繁体   中英

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: 在此处输入图像描述 rotared dendrogram



The plot I get looks like this: 在此处输入图像描述 unrotated dendrogram

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM