I have used this code to make horizontal dendogram but somehow the variables name are not showing properly.
structure(list(Location = c("Plastic", "Foamed Plastics", "Paper & Cardboard", "Rubber", "Cloth", "wood", "Glass & Ceramic", "Metal"), Cox.s.Bazar = c(3072L, 463L, 208L, 177L, 59L, 63L, 62L, 28L), Chittagong = c(1372L, 397L, 402L, 60L, 87L, 27L, 28L, 8L), St..Martin.s.Island = c(1121L, 48L, 216L, 54L, 107L, 74L, 18L, 27L), Kuakata = c(544, 37, 65, 12, 34, 0.1, 17, 0.1), Kotka = c(126, 0.1, 12, 0.1, 3, 0.1, 0.1, 0.1)), class = "data.frame", row.names = c("Plastic", "Foamed Plastics", "Paper & Cardboard", "Rubber", "Cloth", "wood", "Glass & Ceramic", "Metal"))
Code I have used
rownames(df) = c(df$Location)
head(df)
data = df[,-1]
head(data)
mydata = scale(data)
head(mydata)
require(stats)
res.dist = dist(x=mydata, method = "euclidean")
hcl = hclust(d=res.dist, method = "complete")
require(graphics)
plot(as.dendrogram(hcl), xlab ="Height", horiz = T)
You need to set the margin with par(mar = c(...))
# order of margin is bottom, left, top, right - for your case increase the right margin
par(mar = c(5, 5, 5, 15))
plot(as.dendrogram(hcl), xlab ="Height", horiz = T)
ggplot
solution To use ggplot
it required to do some manual for the text if want the text to be on the right side of plot. I found this solution from another answers for your reference I also put the link at bottom.
library("ggplot2")
library("ggdendro")
dendr <- dendro_data(hcl, type="rectangle") # convert for ggplot
clust <- cutree(hcl, k=2) # find 2 clusters
clust.df <- data.frame(label=names(clust), cluster=factor(clust))
# dendr[["labels"]] has the labels, merge with clust.df based on label column
dendr[["labels"]] <- merge(dendr[["labels"]],clust.df, by="label")
# plot the dendrogram; note use of color=cluster in geom_text(...)
ggplot() +
geom_segment(data=segment(dendr), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label(dendr), aes(x, y, label=label, hjust=0, color=cluster),
size=3) +
coord_flip() + scale_y_reverse(expand=c(0.2, 0)) +
theme(axis.line.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.y=element_blank(),
axis.title.y=element_blank(),
panel.background=element_rect(fill="white"),
panel.grid=element_blank())
Created on 2021-05-19 by the reprex package (v2.0.0)
Link to another answer: Colorize Clusters in Dendogram with ggplot2
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.