I can color labels in Python dendrograms but I don't know how to color parts of the links belonging its labels.. I want to make something like this:
Is it possible in Python?
Here I color only labels:
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sc
dists = np.array([[0,2,1,4],[2,0,3,5],[1,3,0,6],[4,5,6,0]])
l = ['a','b','c','b']
Z = sc.linkage(dists, method='complete')
d = sc.dendrogram(Z, labels=l)
label_colors = {'a': 'r', 'b': 'g', 'c': 'm'}
ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for i in range(len(xlbls)):
xlbls[i].set_color(label_colors[xlbls[i].get_text()])
plt.show()
SciPy – Cluster Hierarchy Dendrogram.
cluster. hierarchy ) These functions cut hierarchical clusterings into flat clusterings or find the roots of the forest formed by a cut by providing the flat cluster ids of each observation. fcluster (Z, t[, criterion, depth, R, monocrit])
Not sure if it's possible to color part of an u-shape, however you can color it complete shapes with something like
d = sc.dendrogram(Z, labels=l)
it = iter(map(label_colors.__getitem__, d['ivl'])[-2::-1])
def f(x):
return it.next()
d = sc.dendrogram(Z, labels=l, link_color_func=f)
ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for y in xlbls:
y.set_color(label_colors[y.get_text()])
In Python dendrogram you can not colour a half u-shape directly, but you can appoint colours to any node. This can be accomplished as below:
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sc
dists = np.array([[0,2,1,4],[2,0,3,5],[1,3,0,6],[4,5,6,0],[4,7,6,2]])
Z = sc.linkage(dists, method='complete')
num = len(dists)
color = ["b"]*(2*num-1) # initialize color list with blue
# define the color of a specific node
color[5]="g"
color[6]="r"
color[7]="y"
d = sc.dendrogram(Z,link_color_func=lambda x: color[x])
# add labels for nodes
coord = np.c_[np.array(d['icoord'])[:,1:3],np.array(d['dcoord'])[:,1]]
coord = coord[np.argsort(coord[:,2])]
for posi in coord:
x = 0.5 * sum(posi[0:2])
y = posi[2]
plt.plot(x, y, 'ro')
plt.annotate("%2i" % num, (x, y), xytext=(0, -8),
textcoords='offset points',
va='top', ha='center')
num = num+1
plt.show()
#~ plt.savefig("test.png")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With