python heatmap画热力图怎么设置批注数字的格式
如果要设置热力图中批注数字的格式,可以使用matplotlib中的ticker模块中的FormatStrFormatter类。具体的代码如下:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker
# 构造数据
data = np.random.rand(5, 5)
# 绘制热力图
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='YlOrRd')
# 设置批注数字的格式为小数点后两位
format_str = '%.2f'
formatter = ticker.FormatStrFormatter(format_str)
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
# 添加颜色条
cbar = ax.figure.colorbar(im, ax=ax)
plt.show()
上述代码中,我们首先构造了一个5x5的随机数据矩阵,然后绘制了热力图。接着,我们使用FormatStrFormatter类设置了批注数字的格式为小数点后两位,并将其应用到x轴和y轴上。最后,我们添加了颜色条并显示了热力图。
原文地址: https://www.cveoy.top/t/topic/bb7A 著作权归作者所有。请勿转载和采集!