Numpy matplotlib热图文本数字

Numpy matplotlib热图文本数字,numpy,matplotlib,heatmap,Numpy,Matplotlib,Heatmap,我想用以下数据绘制一张热图,并在上面显示数值。 如果按以下方式绘制图形,则0.000值将显示为0。 我想把0.000写成0.000 import matplotlib.pyplot as plt import numpy as np data = np.array([[0.891, 0.111, 0.000, 0.000, 0.000], [0.027, 0.971, 0.001, 0.000, 0.000], [0.000,

我想用以下数据绘制一张热图,并在上面显示数值。 如果按以下方式绘制图形,则0.000值将显示为0。 我想把0.000写成0.000

import matplotlib.pyplot as plt
import numpy as np

data = np.array([[0.891, 0.111, 0.000, 0.000, 0.000],
                 [0.027, 0.971, 0.001, 0.000, 0.000],
                 [0.000, 0.001, 0.997, 0.001, 0.001],
                 [0.000, 0.000, 0.001, 0.997, 0.002],
                 [0.000, 0.001, 0.005, 0.028, 0.966]])

xlabels = ['label_1', 'label_2', 'label_3', 'label_4', 'label_5']
ylabels = ['label_1', 'label_2', 'label_3', 'label_4', 'label_5']

fig, ax = plt.subplots(figsize=(7,7))

im = ax.imshow(data, cmap='Blues')

ax.set_title("Title", fontsize=16)
ax.set_xticks(np.arange(5))
ax.set_yticks(np.arange(5))

fig.colorbar(im, ax=ax)

for i in range(len(ylabels)):
    for j in range(len(xlabels)):
        if i == j:
            text = ax.text(j, i, data[i,j], ha="center", va="center", color='w')
        else:
            text = ax.text(j, i, data[i,j], ha="center", va="center", color='black')

ax.set_axis_off()
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
plt.show()

使用seaborn可能会更容易:
sns.heatmap(data=data,xticklabels=xlabels,yticklabels=ylabels,square=True,cmap='Blues',annot=True,fmt='.3f',cbar=True,cbar_-kws={shrink':0.8},ax ax)
import matplotlib.pyplot as plt
import numpy as np

data = np.array([[0.891, 0.111, 0.000, 0.000, 0.000],
                 [0.027, 0.971, 0.001, 0.000, 0.000],
                 [0.000, 0.001, 0.997, 0.001, 0.001],
                 [0.000, 0.000, 0.001, 0.997, 0.002],
                 [0.000, 0.001, 0.005, 0.028, 0.966]])

xlabels = ['label_1', 'label_2', 'label_3', 'label_4', 'label_5']
ylabels = ['label_1', 'label_2', 'label_3', 'label_4', 'label_5']

fig, ax = plt.subplots(figsize=(7,7))

im = ax.imshow(data, cmap='Blues')

ax.set_title("Title", fontsize=16)
ax.set_xticks(np.arange(5))
ax.set_yticks(np.arange(5))

fig.colorbar(im, ax=ax)

for i in range(len(ylabels)):
    for j in range(len(xlabels)):
        if i == j:
            text = ax.text(j, i, f"{data[i,j]:.3f}", ha="center", va="center", color='w')
            #    set format here ^^^^^^^^^^^^^^^^^^
        else:
            text = ax.text(j, i, f"{data[i,j]:.3f}", ha="center", va="center", color='black')

ax.set_axis_off()
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
plt.show()