gpt4 book ai didi

matplotlib - 如何根据定义的组为树状图的标签着色? (在 python 中)

转载 作者:行者123 更新时间:2023-12-04 07:27:58 24 4
gpt4 key购买 nike

我想以组的相同颜色生成绘图的标签。我该怎么做?
简单示例测试:

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt


mat = np.array([[1.0, 0.5, 0.0],
[0.5, 1.0, -0.5],
[1.0, -0.5, 0.5],
[0.0, 0.5, -0.5]])

dist_mat = mat
linkage_matrix = linkage(dist_mat, "single")

plt.clf()

ddata = dendrogram(linkage_matrix, color_threshold=0.8)
前面的代码生成了这个图:
enter image description here
但我想要蓝色的 0 和 2 索引和红色的 1 和 3。

最佳答案

import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt


mat = np.array([[1.0, 0.5, 0.0], [0.5, 1.0, -0.5], [1.0, -0.5, 0.5], [0.0, 0.5, -0.5]])

dist_mat = mat
linkage_matrix = linkage(dist_mat, "single")

# plt.clf()

ddata = dendrogram(linkage_matrix, color_threshold=0.8)

# We get the color of leaves from the scipy dendogram docs
# The key is called "leaves_color_list". We iterate over the list of these colors and set colors for our leaves
# Please note that this parameter ("leaves_color_list") is different from the "color_list" which is the color of links
# (as shown in the picture)
# For the latest names of these parameters, please refer to scipy docs
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.dendrogram.html
for leaf, leaf_color in zip(plt.gca().get_xticklabels(), ddata["leaves_color_list"]):
leaf.set_color(leaf_color)
plt.show()
输出如下所示。参数( color_listleaves_color_list )之间的差异已突出显示以显示差异。
enter image description here

关于matplotlib - 如何根据定义的组为树状图的标签着色? (在 python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68122395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com