Dan*_*she 5 python matplotlib seaborn
我正在使用 seaborn (sns.heatmap) 中的热图来显示二进制值真/假的矩阵。它工作得很好,但正如预期的那样,颜色条显示了 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})
Run Code Online (Sandbox Code Playgroud)
这是使用一些随机数据的解决方案(在您在帖子中包含数据之前进行处理)。该解决方案适用于此链接中的问题。
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'])
Run Code Online (Sandbox Code Playgroud)
输出
适用于您的问题:
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(8, 8))
colors = ["gray", "lightgray"]
cmap = LinearSegmentedColormap.from_list('Custom', colors, len(colors))
# Draw the heatmap with the mask and correct aspect ratio
_ = sns.heatmap(df, cmap=cmap,square=True, linewidths=.5, cbar_kws={"shrink": .5})
# Set the colorbar labels
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([0.25,0.75])
colorbar.set_ticklabels(['0', '1'])
Run Code Online (Sandbox Code Playgroud)
输出
| 归档时间: |
|
| 查看次数: |
3040 次 |
| 最近记录: |