A Guide to Dendrograms in Python

FeaImg Dendrograms

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
X = np.random.rand(15, 12) 
fig = ff.create_dendrogram(X)
fig.update_layout(width=800, height=500)
Basic Dendrogram
Basic Dendrogram

Applying Heirarichal Clustering and plotting a Dendrogram

We will utilize the following methods to achieve hierarchical clustering and plot a dendrogram:

  1. The hierarchy module provides routines for hierarchical and agglomerative clustering.
  2. The scipy.cluster.hierarchy.linkage method is used to do hierarchical clustering.
  3. 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')
dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7)
Dendogram HeiCluster Plot
DendrogramsHeiCluster Plot

Change Orientation of Dendrograms

dn = hierarchy.dendrogram(temp, above_threshold_color="green", color_threshold=.7,orientation='right')
Dendogram HeiCluster Plot Right Orientation
DendrogramsHeiCluster Plot Right Orientation


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:

  1. Python Bar Plot – Visualize Categorical Data in Python
  2. How to Load and Plot the MNIST dataset in Python?
  3. Top 5 Best Python Plotting and Graph Libraries

Thank you for taking your time out! Hope you learned something new!! 😄