A dendrogram is a diagram that depicts a tree. The create_dendrogram
figure factory conducts hierarchical clustering on data and depicts the resultant tree. Distances between clusters are represented by the values on the tree depth axis.
Dendrogram plots are often used in computational biology to depict gene or sample grouping, occasionally in the margins of heatmaps.
Hierarchical clustering produces dendrograms as an output. Many people claim that dendrograms of this type may be used to determine the number of clusters. This is true, however, only when the ultrametric tree inequality holds, which is seldom if ever, the case in practice.
Plot a Basic Dendrograms in Python
import plotly.figure_factory as ff
import numpy as np
np.random.seed(1)
X = np.random.rand(15, 12)
fig = ff.create_dendrogram(X)
fig.update_layout(width=800, height=500)
fig.show()

Applying Heirarichal Clustering and plotting a Dendrogram
We will utilize the following methods to achieve hierarchical clustering and plot a dendrogram:
- The hierarchy module provides routines for hierarchical and agglomerative clustering.
- The scipy.cluster.hierarchy.linkage method is used to do hierarchical clustering.
- To plot the hierarchical clustering as a dendrogram scipy.cluster.hierarchy.dendrogram function is used.
import numpy as np
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt
x = np.array([100., 200., 300., 400., 500., 250.,450., 280., 450., 750.])
temp = hierarchy.linkage(x, 'single')
plt.figure()
dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7)

Change Orientation of Dendrograms
dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7,orientation='right')

Conclusion
Congratulations! You just learned how to plot Dendrograms in Python. Hope you enjoyed it! 😇
Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:
- Python Bar Plot – Visualize Categorical Data in Python
- How to Load and Plot the MNIST dataset in Python?
- Top 5 Best Python Plotting and Graph Libraries
Thank you for taking your time out! Hope you learned something new!! 😄