Skip to main content
 首页 » 编程设计

python之在热图中使颜色条值整数 matplotlib seaborn

2024年10月01日8xiaohuochai

我试图让我的颜色条具有整数值而不是小数,但是编码比预期的要难得多。

我的初始代码

import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 
 
#sns.set() 
 
# read data 
revels_data = pd.read_csv("revels2.txt") 
rd = revels_data 
 
revels = rd.pivot("Flavour", "Packet number", "Contents") 
 
# orders flavours  
revels.index = pd.CategoricalIndex(revels.index, categories=["orange", "toffee", "chocolate", "malteser", "raisin", "coffee"]) 
revels.sortlevel(level=0, inplace=True) 
 
# Draw a heatmap with the numeric values in each cell 
ax = sns.heatmap(revels, annot=True, fmt="d", linewidths=0.4, cmap="YlOrRd") 
 
ax.set_title('REVELS PACKET COUNT HEATMAP', weight="bold") 
 
plt.show() 

产生

尝试对此处的答案之一进行逆向工程

添加以下代码

cmap = plt.get_cmap("YlOrRd", np.max(rd.Contents)-np.min(rd.Contents)+1) 
plt.get_cmap("YlOrRd", np.max(rd.Contents)-np.min(rd.Contents)+1) 
 
# set limits .5 outside true range 
mat = plt.matshow(rd.Contents, cmap=cmap, vmin = np.min(rd.Contents)-.5, vmax = np.max(rd.Contents)+.5) 
plt.matshow(rd.Contents ,cmap=cmap, vmin = np.min(rd.Contents)-.5, vmax = np.max(rd.Contents)+.5) 
 
#tell the colorbar to tick at integers 
cax = plt.colorbar(mat, ticks=np.arange(np.min(rd.Contents),np.max(rd.Contents)+1)) 
plt.colorbar(mat, ticks=np.arange(np.min(rd.Contents),np.max(rd.Contents)+1)) 

但出现错误,即 ValueError: 没有足够的值来解包。

我想我可能应用了错误的代码,非常感谢任何帮助。

请您参考如下方法:

这是一个完整的工作示例,它为 seaborn 热图图创建了一个离散的颜色条,其中整数值作为颜色条刻度。

import pandas as pd 
import numpy as np; np.random.seed(8) 
import matplotlib.pyplot as plt 
import seaborn.apionly as sns 
plt.rcParams["figure.figsize"] = 10,5.5 
 
flavours=["orange", "toffee", "chocolate", "malteser", "raisin", "coffee"] 
num = np.arange(0, 6*36).astype(int) % 36 
flavs = np.random.choice(flavours, size=len(num)) 
conts = np.random.randint(0,6, len(num)).astype(int) 
 
df = pd.DataFrame({"Packet number":num ,"Flavour":flavs,"Contents" : conts}) 
 
revels = pd.pivot_table(df, index=["Flavour"], columns=["Packet number"], values="Contents", aggfunc=np.sum)  
revels.index = pd.CategoricalIndex(revels.index, categories=flavours) 
revels.sortlevel(level=0, inplace=True) 
revels= revels.fillna(0) 
 
 
ticks=np.arange(revels.values.min(),revels.values.max()+1 ) 
boundaries = np.arange(revels.values.min()-.5,revels.values.max()+1.5 ) 
cmap = plt.get_cmap("YlOrRd", revels.values.max()-revels.values.min()+1) 
ax = sns.heatmap(revels, annot=True, linewidths=0.4, cmap=cmap, 
        cbar_kws={"ticks":ticks, "boundaries":boundaries}) 
 
ax.set_title('REVELS PACKET COUNT HEATMAP', weight="bold") 
 
plt.tight_layout() 
plt.show()