2

I used hclust and as.dendogram to make a dendrogram, but when I rotate it to a horizontal orientation, the model names are cut off. How can I make sure that the plot shows the entire model names?

my cluster dendogram

  • 2
    You likely need to increase the margin on the right hand side of your plot. The exact implementation details depend on how you're plotting this in the first place. In general, it is recommended to include an [MCVE](https://stackoverflow.com/help/mcve) with your question. – Artem Sokolov Jul 19 '18 at 20:33
  • 1
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 19 '18 at 20:38

2 Answers2

1

You need to play with the margin. Here is an example (it also uses dendextend to give extra control over the color and shape of the dendrogram)

library(dendextend)
library(dplyr)
small_mtcars <- head(mtcars) %>% select(mpg, cyl, disp)
small_mtcars

d1 = small_mtcars %>% dist() %>% hclust(method = "average") %>% as.dendrogram() 
library(colorspace)
some_colors <- rainbow_hcl(nrow(small_mtcars))
d1_col <- some_colors[order.dendrogram(d1)]
# some colors for fun
d1 <- d1     %>% 
        set("labels_cex",1.2) %>% 
        set("labels_colors", value= d1_col) %>% 
        set("leaves_pch", 19) %>%
        set("leaves_cex", 2) %>%
        set("leaves_col", value= d1_col) 

par(mfrow = c(1,2))

par(mar = c(2,2,2,2))
d1 %>% 

    plot(main="d1 (bad margins)", horiz = TRUE)

par(mar = c(2,2,2,10))
d1 %>% 
    set("labels_cex",1.2) %>% 
    plot(main="d1 (good margins)", horiz = TRUE)

enter image description here

Tal Galili
  • 24,605
  • 44
  • 129
  • 187
0

You can also use plot.phylo from package:ape (Analyses of Phylogenetics and Evolution):

library("ape")
png("out.png",w=350,h=200)
a<-as.phylo(hclust(dist(scale(head(mtcars)[,c("mpg","cyl","disp")]))))
plot(a,cex=1.3,no.margin=T,font=1)
dev.off()

font=1 uses a regular font instead of italic.

no.margin=T removes vertical margins but it still keeps horizontal margins. I used ImageMagick to remove the horizontal margins and to add a small 10px margin around the plot: mogrify -trim -border 10 -bordercolor white out.png.

cex (character expansion) changes text size.

Underscores are replaced with spaces in labels by default without underscore=T.

?plot.phylo shows further options.

nisetama
  • 7,764
  • 1
  • 34
  • 21