9951 explained code solutions for 126 technologies


python-scipyHow do I create a dendrogram using Python and SciPy?


The dendrogram is a graphical representation of a hierarchical structure (e.g. a tree) that is commonly used to represent the relationships between data points in a dataset. It can be created using Python and SciPy with the following steps:

  1. Import the necessary libraries:
import scipy.cluster.hierarchy as sch
from matplotlib import pyplot as plt
  1. Create the data to be used in the dendrogram. For example, a 2x3 matrix:
data = [[2, 3, 4], [5, 6, 7]]
  1. Use the SciPy library to generate the linkage matrix:
Z = sch.linkage(data, 'ward')
  1. Generate the dendrogram using the linkage matrix:
dendrogram = sch.dendrogram(Z)
  1. Plot the dendrogram:
plt.show()

The resulting dendrogram will look like this:

Dendrogram

Helpful links

Edit this code on GitHub