2016-10-04 124 views
2

我想通過使用ggplot2創建一個漂亮的樹狀圖。ggplot2上的軸上的顏色軸標籤或繪製矩形

這是我在做什麼重複的例子:

library(ggplot2) 
library(ggdendro) 
data(mtcars) 
x <- as.matrix(scale(mtcars)) 
dd.row <- as.dendrogram(hclust(dist(t(x)))) 

mtcars_dendrogram <- ggdendrogram(dd.row, rotate = TRUE, theme_dendro = FALSE) + 
    labs(x="", y="Distance") + 
    ggtitle("Mtcars Dendrogram") + 
    theme(panel.border = element_rect(colour = "black", fill=NA, size=.5), 
     axis.text.x=element_text(colour="black", size = 10), 
     axis.text.y=element_text(colour="black", size = 10), 
     legend.key=element_rect(fill="white", colour="white"), 
     legend.position="bottom", legend.direction="horizontal", 
     legend.title = element_blank(), 
     panel.grid.major = element_line(colour = "#d3d3d3"), 
     panel.grid.minor = element_blank(), 
     panel.border = element_blank(), 
     panel.background = element_blank(), 
     plot.title = element_text(size = 14, family = "Tahoma", face = "bold"), 
     text=element_text(family="Tahoma")) 
mtcars_dendrogram <- mtcars_dendrogram + 
    annotate("rect", xmin = 0.6, xmax = 5.4, ymin = 0, ymax = 6.4, fill="red", colour="red", alpha=0.1) + 
    annotate("rect", xmin = 5.6, xmax = 7.4, ymin = 0, ymax = 6.4, fill="blue", colour="blue", alpha=0.1) + 
    annotate("rect", xmin = 7.6, xmax = 11.4, ymin = 0, ymax = 6.4, fill="orange", colour="orange", alpha=0.1) + 
    geom_hline(yintercept = 6.4, color = "blue", size=1, linetype = "dotted") 
mtcars_dendrogram 

這是結果

mtcars_dendrogram

我想擴展矩形,以便它涵蓋x軸。如果我改變,例如,

annotate("rect", xmin = 5.6, xmax = 7.4, ymin = 0, ymax = 6.4, fill="blue", colour="blue", alpha=0.1) 

annotate("rect", xmin = 5.6, xmax = 7.4, ymin = -1, ymax = 6.4, fill="blue", colour="blue", alpha=0.1) 

然後我得到這個

mtcars_dendrogram_2

這是我想獲得(這一結果與Photoshop改變)什麼

mtcars_dendrogram_3

任何幫助非常歡迎。非常感謝。

回答

1

您可以僞造的左軸:

mtcars_dendrogram <- mtcars_dendrogram + 
annotate("rect", xmin = 0.6, xmax = 5.4, ymin = -1, ymax = 6.4, fill="red", colour="red", alpha=0.1) + 
    annotate("rect", xmin = 5.6, xmax = 7.4, ymin = -1, ymax = 6.4, fill="blue", colour="blue", alpha=0.1) + 
    annotate("rect", xmin = 7.6, xmax = 11.4, ymin = -1, ymax = 6.4, fill="orange", colour="orange", alpha=0.1) + 
    geom_hline(yintercept = 6.4, color = "blue", size=1, linetype = "dotted") + 
    theme(axis.text.y = element_blank(), 
     axis.line.y = element_blank(), 
     axis.ticks.y = element_blank()) + 
    geom_text(aes(y = 0, x = 1:11, 
       label = c("carb", "wt", "hp", "cyl", "disp", "qsec", "vs", "mpg", "drat", "am", "gear")), 
      hjust = "right", 
      nudge_y = -.1)) 

enter image description here