python - 类似热图的图,但用于 seaborn 中的分类变量

标签 python matplotlib seaborn

heatmap-like plot, but for categorical variables 相同的问题但使用 python 和 seaborn 而不是 R:

假设我有以下数据框:

df = pd.DataFrame({"John":"No Yes Maybe".split(),
                   "Elly":"Yes Yes Yes".split(),
                   "George":"No Maybe No".split()},
                   index="Mon Tue Wed".split())

现在我想绘制一个热图并根据每个单元格的相应值为其着色。即"is"、“否”、“也许”,例如变为“绿色”、“灰色”、“黄色”。图例应具有这三种颜色和相应的值。

我自己通过以下方式解决了这个问题。我似乎无法将分类颜色图传递给 seaborn 的热图,所以我用数字替换所有文本,然后在内部重建 seaborn 使用的颜色图,即:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches

# create dictionary with value to integer mappings
value_to_int = {value: i for i, value in enumerate(sorted(pd.unique(df.values.ravel())))}

f, ax = plt.subplots()
hm = sns.heatmap(df.replace(value_to_int).T, cmap="Pastel2", ax=ax, cbar=False)
# add legend
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])
legend_ax = f.add_axes([.7, .5, 1, .1])
legend_ax.axis('off')
# reconstruct color map
colors = plt.cm.Pastel2(np.linspace(0, 1, len(value_to_int)))
# add color map to legend
patches = [mpatches.Patch(facecolor=c, edgecolor=c) for c in colors]
legend = legend_ax.legend(patches,
    sorted(value_to_int.keys()),
    handlelength=0.8, loc='lower left')
for t in legend.get_texts():
    t.set_ha("left")

Categorical heatmap in seaborn

我的问题:是否有更简洁的方法来制作此热图?如果没有,这可能是一个值得实现的功能,在这种情况下,我会将其发布在 seaborn 问题跟踪器上。

最佳答案

您可以使用离散颜色图并修改颜色条,而不是使用图例。

value_to_int = {j:i for i,j in enumerate(pd.unique(df.values.ravel()))} # like you did
n = len(value_to_int)     
# discrete colormap (n samples from a given cmap)
cmap = sns.color_palette("Pastel2", n) 
ax = sns.heatmap(df.replace(value_to_int), cmap=cmap) 
# modify colorbar:
colorbar = ax.collections[0].colorbar 
r = colorbar.vmax - colorbar.vmin 
colorbar.set_ticks([colorbar.vmin + r / n * (0.5 + i) for i in range(n)])
colorbar.set_ticklabels(list(value_to_int.keys()))                                          
plt.show()

categorical seaborn heatmap

colorbar部分改编自this answer

HTH

关于python - 类似热图的图,但用于 seaborn 中的分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227475/

相关文章:

python - 如果特定键的值相同,则合并字典

python - 取消屏蔽最后打印的表达式变量

Python:绘制逐月归一化直方图

python-3.x - 错误:import seaborn- while running the program : from . _ufuncs import * ImportError:DLL加载失败:找不到指定的模块

python - 遍历时从字符串列表中删除元素

python - 类型错误 : unhashable type on new computer but not old

python - Matplotlib:如何绘制图像而不是点?

python - 改变图像的深度?

python - 从有序数据集中提取连接线

python - 如何将 seaborn 图保存为 svg 或 png