在热图matplotlib seaborn中使colorbar值整数

时间:2017-04-29 15:12:52

标签: python matplotlib seaborn colorbar

我正在尝试使我的颜色栏具有整数值而不是小数,但编码比预期的要困难得多。

我的初始代码

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

产生

enter image description here

尝试从这里反向设计其中一个答案

添加以下代码

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:没有足够的值来解包。

我想我可能已经错误地应用了代码,感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

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

enter image description here

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