如何在python中使用scipy为树形图中的部分链接着色?

时间:2013-12-15 23:46:11

标签: python colors scipy dendrogram

我可以在Python树形图中为标签着色,但我不知道如何为属于其标签的链接添加部分颜色..我想做这样的事情:

http://winedarksea.org/wp-content/uploads/2009/11/PCCovariance1and2WardDendrogram1-815x1024.jpg

在Python中可以吗?

这里我只为标签着色:

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()

2 个答案:

答案 0 :(得分:1)

不确定是否可以为U形的部分着色,但是您可以使用

之类的东西
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()])

enter image description here

答案 1 :(得分:1)

在Python树形图中,您不能直接为半个U形着色,但可以为任何节点指定颜色。这可以通过以下方式实现:

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")

enter image description here