写一段python代码画出矩阵C的热力图数字标注通过A矩阵实现
这里提供一个使用matplotlib库绘制热力图的示例代码:
import matplotlib.pyplot as plt
import numpy as np
# 定义矩阵A和矩阵C,这里仅假设A和C都是3x3的矩阵
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
C = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])
# 绘制热力图
fig, ax = plt.subplots()
im = ax.imshow(C, cmap='BuPu')
# 添加数字标注
for i in range(len(C)):
for j in range(len(C[0])):
text = ax.text(j, i, A[i][j], ha="center", va="center", color="w")
# 设置坐标轴标签
ax.set_xticks(np.arange(len(C[0])))
ax.set_yticks(np.arange(len(C)))
ax.set_xticklabels(['col'+str(i) for i in range(1, len(C[0])+1)])
ax.set_yticklabels(['row'+str(i) for i in range(1, len(C)+1)])
# 添加颜色条
cbar = ax.figure.colorbar(im, ax=ax)
# 设置图像标题和保存图像
ax.set_title("Heatmap of matrix C")
plt.savefig("heatmap.png")
plt.show()
其中,通过imshow函数绘制热力图,text函数添加数字标注,set_xticklabels和set_yticklabels函数设置坐标轴标签,colorbar函数添加颜色条。最后,通过savefig函数保存图像,通过show函数显示图像。需要注意的是,这里假设A和C都是3x3的矩阵,如果是其他大小的矩阵,需要相应地修改代码。
原文地址: https://www.cveoy.top/t/topic/bhgX 著作权归作者所有。请勿转载和采集!