【问题标题】:matplotlib heatmap text digitmatplotlib 热图文本数字
【发布时间】:2021-07-19 17:08:05
【问题描述】:

我想用以下数据绘制热图并在上面显示值。 如果按如下方式绘制图形,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)

标签: numpy matplotlib heatmap


【解决方案1】:
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()

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2013-03-20
    • 2015-05-05
    • 2021-01-14
    • 2021-01-14
    • 1970-01-01
    • 2017-04-23
    • 2020-09-22
    相关资源
    最近更新 更多