matshow
标签详解matshow
是 Matplotlib 中用于可视化二维数组(矩阵)的函数,它会将数组的值映射为颜色,生成一个矩阵图。与 imshow
类似,但 matshow
专门为矩阵可视化设计,会自动添加行列标签和网格线。
import numpy as np
import matplotlib.pyplot as plt
matrix = np.random.rand(5, 5)
fig, ax = plt.subplots()
cax = ax.matshow(matrix)
# 设置行标签
ax.set_xticks(range(5))
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E'])
# 设置列标签
ax.set_yticks(range(5))
ax.set_yticklabels(['1', '2', '3', '4', '5'])
plt.show()
# 旋转x轴标签45度
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E'], rotation=45)
# 旋转y轴标签
ax.set_yticklabels(['1', '2', '3', '4', '5'], rotation=90)
cbar = fig.colorbar(cax)
cbar.set_label('Value Scale')
原因:标签文字过长或矩阵维度太大
解决方案:
plt.figure(figsize=(10, 8)) # 增大图形尺寸
ax.set_xticklabels(labels, rotation=45, fontsize=8) # 旋转并减小字体
原因:默认的刻度位置与矩阵维度不匹配
解决方案:
ax.set_xticks(np.arange(matrix.shape[1])) # 明确设置x刻度位置
ax.set_yticks(np.arange(matrix.shape[0])) # 明确设置y刻度位置
解决方案:
ax.grid(False) # 关闭网格线
# 或
ax.grid(True, linestyle='--', alpha=0.5) # 设置虚线并降低透明度
import numpy as np
import matplotlib.pyplot as plt
# 创建数据
data = np.random.rand(10, 12)
row_labels = [f'Row {i}' for i in range(1, 11)]
col_labels = [f'Col {chr(65+i)}' for i in range(12)]
# 创建图形
fig, ax = plt.subplots(figsize=(12, 8))
# 绘制矩阵
cax = ax.matshow(data, cmap='viridis')
# 设置标签
ax.set_xticks(np.arange(data.shape[1]), labels=col_labels)
ax.set_yticks(np.arange(data.shape[0]), labels=row_labels)
# 旋转x标签
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
# 添加颜色条
cbar = fig.colorbar(cax)
cbar.set_label('Value')
# 添加标题
ax.set_title('Matrix Visualization with Labels')
# 显示网格
ax.grid(True, linestyle=':', alpha=0.3)
plt.tight_layout()
plt.show()