使热图matplotlib seaborn中的colorbar值为整数

2024-05-28 12:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的初始代码

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

试图从这里对其中一个答案进行逆向工程

通过添加以下代码

^{pr2}$

但是获取错误,即ValueError:没有足够的值来解包。在

我想我可能用错了代码,希望你能帮我。在


Tags: 代码importtruereaddataindexasplt
1条回答
网友
1楼 · 发布于 2024-05-28 12:18:08

下面是一个完整的工作示例,它为seaborn热图图图创建一个离散的colorbar,其中的整数值作为colorbar记号。在

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

相关问题 更多 >