bundles / scipy 1.17.1 / scipy / cluster / hierarchy / dendrogram
function
scipy.cluster.hierarchy:dendrogram
Signature
def dendrogram ( Z , p = 30 , truncate_mode = None , color_threshold = None , get_leaves = True , orientation = top , labels = None , count_sort = False , distance_sort = False , show_leaf_counts = True , no_plot = False , no_labels = False , leaf_font_size = None , leaf_rotation = None , leaf_label_func = None , show_contracted = False , link_color_func = None , ax = None , above_threshold_color = C0 ) Summary
Plot the hierarchical clustering as a dendrogram.
Extended Summary
The dendrogram illustrates how each cluster is composed by drawing a U-shaped link between a non-singleton cluster and its children. The top of the U-link indicates a cluster merge. The two legs of the U-link indicate which clusters were merged. The length of the two legs of the U-link represents the distance between the child clusters. It is also the cophenetic distance between original observations in the two children clusters.
Parameters
Z: ndarrayThe linkage matrix encoding the hierarchical clustering to render as a dendrogram. See the
linkagefunction for more information on the format ofZ.p: int, optionalThe
pparameter fortruncate_mode.truncate_mode: str, optionalThe dendrogram can be hard to read when the original observation matrix from which the linkage is derived is large. Truncation is used to condense the dendrogram. There are several modes:
NoneNo truncation is performed (default). Note:
'none'is an alias forNonethat's kept for backward compatibility.'lastp'The last
pnon-singleton clusters formed in the linkage are the only non-leaf nodes in the linkage; they correspond to rowsZ[n-p-2:end]inZ. All other non-singleton clusters are contracted into leaf nodes.'level'No more than
plevels of the dendrogram tree are displayed. A "level" includes all nodes withpmerges from the final merge.Note:
'mtica'is an alias for'level'that's kept for backward compatibility.
color_threshold: double, optionalFor brevity, let be the
color_threshold. Colors all the descendent links below a cluster node the same color if is the first node below the cut threshold . All links connecting nodes with distances greater than or equal to the threshold are colored with de default matplotlib color'C0'. If is less than or equal to zero, all nodes are colored'C0'. Ifcolor_thresholdis None or 'default', corresponding with MATLAB(TM) behavior, the threshold is set to0.7*max(Z[:,2]).get_leaves: bool, optionalIncludes a list
R['leaves']=Hin the result dictionary. For each ,H[i] == j, cluster nodejappears in positioniin the left-to-right traversal of the leaves, where and .orientation: str, optionalThe direction to plot the dendrogram, which can be any of the following strings:
'top'Plots the root at the top, and plot descendent links going downwards. (default).
'bottom'Plots the root at the bottom, and plot descendent links going upwards.
'left'Plots the root at the left, and plot descendent links going right.
'right'Plots the root at the right, and plot descendent links going left.
labels: ndarray, optionalBy default,
labelsis None so the index of the original observation is used to label the leaf nodes. Otherwise, this is an -sized sequence, withn == Z.shape[0] + 1. Thelabels[i]value is the text to put under the th leaf node only if it corresponds to an original observation and not a non-singleton cluster.count_sort: str or bool, optionalFor each node n, the order (visually, from left-to-right) n's two descendent links are plotted is determined by this parameter, which can be any of the following values:
FalseNothing is done.
'ascending'orTrueThe child with the minimum number of original objects in its cluster is plotted first.
'descending'The child with the maximum number of original objects in its cluster is plotted first.
Note,
distance_sortandcount_sortcannot both be True.distance_sort: str or bool, optionalFor each node n, the order (visually, from left-to-right) n's two descendent links are plotted is determined by this parameter, which can be any of the following values:
FalseNothing is done.
'ascending'orTrueThe child with the minimum distance between its direct descendents is plotted first.
'descending'The child with the maximum distance between its direct descendents is plotted first.
Note
distance_sortandcount_sortcannot both be True.show_leaf_counts: bool, optionalWhen True, leaf nodes representing original observation are labeled with the number of observations they contain in parentheses.
no_plot: bool, optionalWhen True, the final rendering is not performed. This is useful if only the data structures computed for the rendering are needed or if matplotlib is not available.
no_labels: bool, optionalWhen True, no labels appear next to the leaf nodes in the rendering of the dendrogram.
leaf_rotation: double, optionalSpecifies the angle (in degrees) to rotate the leaf labels. When unspecified, the rotation is based on the number of nodes in the dendrogram (default is 0).
leaf_font_size: int, optionalSpecifies the font size (in points) of the leaf labels. When unspecified, the size based on the number of nodes in the dendrogram.
leaf_label_func: lambda or function, optionalWhen
leaf_label_funcis a callable function, for each leaf with cluster index . The function is expected to return a string with the label for the leaf.Indices correspond to original observations while indices correspond to non-singleton clusters.
For example, to label singletons with their node id and non-singletons with their id, count, and inconsistency coefficient, simply do
# First define the leaf label function. def llf(id): if id < n: return str(id) else: return '[%d %d %1.2f]' % (id, count, R[n-id,3]) # The text for the leaf nodes is going to be big so force # a rotation of 90 degrees. dendrogram(Z, leaf_label_func=llf, leaf_rotation=90) # leaf_label_func can also be used together with ``truncate_mode``, # in which case you will get your leaves labeled after truncation: dendrogram(Z, leaf_label_func=llf, leaf_rotation=90, truncate_mode='level', p=2)
show_contracted: bool, optionalWhen True the heights of non-singleton nodes contracted into a leaf node are plotted as crosses along the link connecting that leaf node. This really is only useful when truncation is used (see
truncate_modeparameter).link_color_func: callable, optionalIf given,
link_color_functionis called with each non-singleton id corresponding to each U-shaped link it will paint. The function is expected to return the color to paint the link, encoded as a matplotlib color string code. For exampledendrogram(Z, link_color_func=lambda k: colors[k])colors the direct links below each untruncated non-singleton node
kusingcolors[k].ax: matplotlib Axes instance, optionalIf None and
no_plotis not True, the dendrogram will be plotted on the current axes. Otherwise ifno_plotis not True the dendrogram will be plotted on the givenAxesinstance. This can be useful if the dendrogram is part of a more complex figure.above_threshold_color: str, optionalThis matplotlib color string sets the color of the links above the color_threshold. The default is
'C0'.
Returns
R: dictA dictionary of data structures computed to render the dendrogram. Its has the following keys:
'color_list'A list of color names. The k'th element represents the color of the k'th link.
'icoord'and'dcoord'Each of them is a list of lists. Let
icoord = [I1, I2, ..., Ip]whereIk = [xk1, xk2, xk3, xk4]anddcoord = [D1, D2, ..., Dp]whereDk = [yk1, yk2, yk3, yk4], then the k'th link painted is(xk1, yk1)-(xk2, yk2)-(xk3, yk3)-(xk4, yk4).'ivl'A list of labels corresponding to the leaf nodes.
'leaves'For each i,
H[i] == j, cluster nodejappears in positioniin the left-to-right traversal of the leaves, where and . Ifjis less thann, thei-th leaf node corresponds to an original observation. Otherwise, it corresponds to a non-singleton cluster.'leaves_color_list'A list of color names. The k'th element represents the color of the k'th leaf.
Notes
It is expected that the distances in Z[:,2] be monotonic, otherwise crossings appear in the dendrogram.
Array API Standard Support
dendrogram has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable SCIPY_ARRAY_API=1 and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.
==================== ==================== ==================== Library CPU GPU ==================== ==================== ==================== NumPy ✅ n/a CuPy n/a ⛔ PyTorch ✅ ⛔ JAX ⚠️ no JIT ⛔ Dask ⚠️ computes graph n/a ==================== ==================== ====================
See
dev-arrayapifor more information.
Examples
import numpy as np from scipy.cluster import hierarchy import matplotlib.pyplot as plt✓
ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754., 564., 138., 219., 869., 669.]) Z = hierarchy.linkage(ytdist, 'single')✓
plt.figure()
✗dn = hierarchy.dendrogram(Z)
✓hierarchy.set_link_color_palette(['m', 'c', 'y', 'k']) fig, axes = plt.subplots(1, 2, figsize=(8, 3)) dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y', orientation='top') dn2 = hierarchy.dendrogram(Z, ax=axes[1], above_threshold_color='#bcbddc', orientation='right') hierarchy.set_link_color_palette(None) # reset to default after use plt.show()✓


See also
- linkage
- set_link_color_palette
Aliases
-
scipy.cluster.hierarchy.dendrogram