I tried plotting a colorful dendrogram to include in my thesis, and it all works just fine apart from one thing: changing the font. I plotted many dendrograms before, and changing the font was never a problem, but in this code it suddenly is... I probably tried to write family="serif" in about any space possible, but idoes not work. My code:
dencw3m <- as.dendrogram(aggl.clust.manhattan.ward.cw3m)
dendro.col.cw3m <- dencw3m %>%
set("branches_k_color", k = 5, value = c("blue", "red", "limegreen", "gold", "darkorange")) %>%
set("branches_lwd", 0.6) %>%
set("labels_colors",
value = c("darkslategray")) %>%
set("labels_cex", 0.5)
gg.cw3m <- as.ggdend(dendro.col.cw3m)
ggplot(gg.cw3m, theme = theme_minimal()) +
labs(x = "Fall", y = "Homogenität", title = "Dendrogramm cw3m", family = "serif", cex = 0.4, hang = -1)
I'm not familiar with the dendextend package, so not sure whether it offers an easy option to set the font family via an argument. However, as the final result is a ggplot object, one option to achieve your desired result would be to manually set the family parameter of the geom_text layer used to add the labels.
Making use of the default example from ?ggdend:
library(dendextend)
library(ggplot2)
dend <- iris[1:30, -5] %>%
dist() %>%
hclust() %>%
as.dendrogram() %>%
set("branches_k_color", k = 5, value = c("blue", "red", "limegreen", "gold", "darkorange")) %>%
set("branches_lwd", 0.6) %>%
set("labels_colors",
value = c("darkslategray")) %>%
set("labels_cex", 0.5)
ggd1 <- as.ggdend(dend, theme = theme_minimal())
p <- ggplot(ggd1)
Having a look at the layers of p we see that the geom_text is the third layer:
p$layers
#> [[1]]
#> mapping: xend = ~xend, yend = ~yend, colour = ~col, linetype = ~lty, size = ~lwd, x = ~x, y = ~y
#> geom_segment: arrow = NULL, arrow.fill = NULL, lineend = square, linejoin = round, na.rm = TRUE
#> stat_identity: na.rm = TRUE
#> position_identity
#>
#> [[2]]
#> mapping: colour = ~col, shape = ~pch, size = ~cex, x = ~x, y = ~y
#> geom_point: na.rm = TRUE
#> stat_identity: na.rm = TRUE
#> position_identity
#>
#> [[3]]
#> mapping: label = ~label, colour = ~col, size = ~cex, x = ~x, y = ~y
#> geom_text: parse = FALSE, check_overlap = FALSE, na.rm = FALSE
#> stat_identity: na.rm = FALSE
#> position_identity
Hence, to switch the font family we could set the family argument of the aes_params of this layer like so:
p$layers[[3]]$aes_params$family <- "serif"
p

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With