gpt4 book ai didi

python - seaborn 热图中的自定义调色板间隔

转载 作者:行者123 更新时间:2023-12-04 12:01:08 25 4
gpt4 key购买 nike

我正在尝试绘制 heatmap使用seaborn库。

绘图函数如下所示:

def plot_confusion_matrix(data, labels, **kwargs):
"""Visualize confusion matrix as a heat map."""
col_map = kwargs.get('color_palette', sns.light_palette('navy', n_colors=5, as_cmap=False))

sns.heatmap(
vmin=0.0,
vmax=1.0,
data=data,
cmap=col_map,
xticklabels=labels,
yticklabels=labels,
linewidths=0.75,
)
data的直方图,然而,看起来像这样:
Histogram

现在我正在努力解决的问题是 seaborn 热图(查看波纹管)均匀地分割色标,因此大多数数据具有相同的颜色(因为数据分布不均匀)。

我无法找到如何为颜色级别设置某种间隔或边界。

假设我有以下十六进制颜色值数组:
['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080']
有没有办法设置颜色,例如
[(threshold_0, hex_0), (threshold_1, hex_1), ..., (threshold_n, hex_n)]
哪里 threshold_i是 [0, 1) 范围内的值

感谢任何帮助。

PS:用于说明的当前热图:

enter image description here

最佳答案

关于本文档 here ,您可以创建自己的颜色词典。这些 dicts 必须是 rgb 值,所以我写了第一个测试函数来从 Hex_colors 和你想要的阈值生成一个:

def NonLinCdict(steps, hexcol_array):
cdict = {'red': (), 'green': (), 'blue': ()}
for s, hexcol in zip(steps, hexcol_array):
rgb =matplotlib.colors.hex2color(hexcol)
cdict['red'] = cdict['red'] + ((s, rgb[0], rgb[0]),)
cdict['green'] = cdict['green'] + ((s, rgb[1], rgb[1]),)
cdict['blue'] = cdict['blue'] + ((s, rgb[2], rgb[2]),)
return cdict

hc = ['#e5e5ff', '#acacdf', '#7272bf', '#39399f', '#000080']
th = [0, 0.1, 0.5, 0.9, 1]

cdict = NonLinCdict(th, hc)
cm = mc.LinearSegmentedColormap('test', cdict)

plt.figure()
sns.heatmap(
vmin=0.0,
vmax=1.0,
data=data,
cmap=cm,
linewidths=0.75)

它产生:

enter image description here

可以做更多的事情(例如,对于离散跳转,只需查看文档...)但这应该可以回答您的原始问题-这次包括“自定义”...

但是,我必须补充一下我的个人意见:像这样拉伸(stretch)的颜色图在这里可能会“令人愉悦”,但应该注意它们不会误导观众的眼睛。

我希望这有帮助。

关于python - seaborn 热图中的自定义调色板间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192121/

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