类似于热图的图未显示正确的颜色

时间:2020-11-12 12:48:08

标签: python pandas dataframe matplotlib seaborn

我有一个数据框df,其中包含该列表['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']中的一些值,但有时并非所有值都出现在df中,例如:

df = pd.DataFrame([['a','b','c'],['b','c','e'],['a', 'e', 'f']])

我使用以下代码绘制了df的类似热图的图:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd

data = [['a','b','c'],['b','c','e'],['a', 'e', 'f']]
df = pd.DataFrame(data)

value = ['a','b','c', 'd', 'e', 'f', 'g', 'h', 'i','j']

value_to_int = {j:i for i,j in enumerate(value)}

n = len(value_to_int)     

#color for value
cmap = ['#b3e6b3', '#66cc66', '#2d862d', '#ffc299','#ff944d', '#ff6600','#ccddff','#99bbff','#4d88ff','#0044cc']

# plot
fig, ax = plt.subplots(figsize = (5, 5)) 
ax = sns.heatmap(df.replace(value_to_int), cmap=cmap,  linewidths = 0.005, annot = False) 

#add value into plot
text = df.to_numpy()
for r in range(text.shape[0]):
    for c in range(text.shape[1]):
        ax.text(c+0.5,r+0.5, text[r,c], 
                va='center',ha='center')

# 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()

但是我得到的图不正确,颜色不符合值,例如'c'应该是深绿色,而热图上的颜色是橙色,等等。

enter image description here

如何修改代码以显示正确的颜色?非常感谢

1 个答案:

答案 0 :(得分:1)

简短答案:将vmin=0, vmax=9添加到sns.heatmap通话中。它与图形和颜色栏的比例有关。

相关问题