有没有办法把seaborn的颜色条(cbar)改成一个传奇(二进制热图)?

2024-04-20 10:05:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用seaborn的热图(sns.热图)显示二进制值的矩阵真/假。它工作得很好,但是颜色条显示的值范围是0-1(实际上只有两种颜色)。在

有没有办法把它改成显示真/假颜色的图例?我在文件里找不到任何东西

https://seaborn.pydata.org/generated/seaborn.heatmap.html

示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'a':[False,True,False,True,True,True],
                   'b':[False,False,False,False,True,False],
                   'c':[False,True,True,False,True,True],
                   'd':[False,True,False,True,True,True],
                   'e':[False,True,True,False,False,True],
                   'f':[False,True,False,False,True,True]})


# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(13, 13))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(300, 180, as_cmap=True)

# Draw the heatmap with the mask and correct aspect ratio
_ = sns.heatmap(df, cmap=cmap, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5})

Tags: theimportfalsetruedfmatplotlib颜色as
1条回答
网友
1楼 · 发布于 2024-04-20 10:05:34

这里有一个使用一些随机数据的解决方案(在你的帖子中包含数据之前,先处理这个问题)。该解决方案适用于从this链接解决您的问题。在

from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import random
import seaborn as sns
sns.set()

# Generate data
uniform_data = np.array([random.randint(0, 1) for _ in range(120)]).reshape((10, 12))

# Define colors
colors = ((1.0, 1.0, 0.0), (1, 0.0, 1.0))
cmap = LinearSegmentedColormap.from_list('Custom', colors, len(colors))

ax = sns.heatmap(uniform_data, cmap=cmap)

# Set the colorbar labels
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([0.25,0.75])
colorbar.set_ticklabels(['0', '1'])

输出

enter image description here

应用于您的问题:

^{pr2}$

输出

enter image description here

相关问题 更多 >