用python写一段绘制矩阵图的代码
时间: 2023-04-07 17:05:26 浏览: 261
以下是用Python绘制矩阵图的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
data = np.random.rand(10, 10)
# 绘制矩阵图
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='coolwarm')
# 设置坐标轴标签
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'])
ax.set_yticklabels(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
# 在矩阵格子中添加数值标签
for i in range(data.shape[0]):
for j in range(data.shape[1]):
text = ax.text(j, i, '{:.2f}'.format(data[i, j]),
ha='center', va='center', color='w')
# 添加颜色条
cbar = ax.figure.colorbar(im, ax=ax)
# 设置图像标题
ax.set_title('Matrix Plot')
# 显示图像
plt.show()
```
希望能对您有所帮助!
阅读全文