I try to add colored rectangle to dendrogram results like as follow:
this is my dendrogram codes:
JavaScript
x
17
17
1
from scipy.cluster.hierarchy import dendrogram
2
3
plt.figure(figsize=(250, 100))
4
labelsize=20
5
ticksize=15
6
plt.title(file_name.split(".")[0], fontsize=labelsize)
7
plt.xlabel('stock', fontsize=labelsize)
8
plt.ylabel('distance', fontsize=labelsize)
9
dendrogram(
10
Z,
11
leaf_rotation=90., # rotates the x axis labels
12
leaf_font_size=8., # font size for the x axis labels
13
labels = corr.columns
14
)
15
pylab.yticks(fontsize=ticksize)
16
pylab.xticks(rotation=-90, fontsize=ticksize)
17
However, this is only add colorful line not a rectangle like in the above image. How can I create image like this?
Thanks
Advertisement
Answer
You can loop through the generated path collections and draw a bounding box.
Optionally, you could set the height to the color_threshold=
parameter, which defaults to Z[:, 2].max() * 0.7
.
The last collection is are the unclassified lines, so the example code below loops through all earlier collections.
JavaScript
1
25
25
1
import matplotlib.pyplot as plt
2
from scipy.cluster import hierarchy
3
import numpy as np
4
5
N = 15
6
ytdist = np.random.randint(10, 1000, N * (N + 1) // 2)
7
Z = hierarchy.linkage(ytdist)
8
9
fig, ax = plt.subplots(1, 1, figsize=(8, 3))
10
dn1 = hierarchy.dendrogram(Z, ax=ax)
11
12
for coll in ax.collections[:-1]: # the last collection is the ungrouped level
13
xmin, xmax = np.inf, -np.inf
14
ymax = -np.inf
15
for p in coll.get_paths():
16
box = p.get_extents()
17
(x0, _), (x1, y1) = p.get_extents().get_points()
18
xmin = min(xmin, x0)
19
xmax = max(xmax, x1)
20
ymax = max(ymax, y1)
21
rec = plt.Rectangle((xmin - 4, 0), xmax - xmin + 8, ymax*1.05,
22
facecolor=coll.get_color()[0], alpha=0.2, edgecolor="none")
23
ax.add_patch(rec)
24
plt.show()
25