使用matplotlib绘图时,特别是对数值矩阵画热力图,很多时候因为设置的画布、坐标轴、分辨率等影响输出图片的维度,使得输出图片的维度无法进行下一步的任务。这里通过设计程序实现输出图片的分辨率和矩阵维度完全一致。
注意事项
import matplotlib.pyplot as plt
1.只能使用plt.figure,不能使用plt.subplot,不然那会有去不掉的边框
2.必须设置dpi为1
h, w = mat.shape
fig = plt.figure(figsize=(w, h), dpi=1)
3.需要设置网格ax
ax = fig.add_subplot([0, 0, 1, 1])
# 这里表示x[0, 1], y[0, 1],即对图像全覆盖
ax = matshow(mat, cmap="jet")
4.有可能需要翻转图像,设置ax.invert_yaxis()
ax.invert_yaxis()
5.需要关闭显示坐标轴
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
6.需要在保存时去掉外面所有可能得边框
# 需要自己设置存储路径
plt.savefig("test.png", dpi=1, bbox_inches="tight", pad_inches=0)
完整代码
import matplotlib.pyplot as plt
def drawmatrix(mat):
h, w = mat.shape
fig = plt.figure(figsize=(w, h), dpi=1)
ax = fig.add_subplot([0, 0, 1, 1])
# 这里表示x[0, 1], y[0, 1],即对图像全覆盖
ax = matshow(mat, cmap="jet")
ax.invert_yaxis()
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
# 需要自己设置存储路径
plt.savefig("test.png", dpi=1, bbox_inches="tight", pad_inches=0)
个人博客:https://kecilimu-notion.vercel.app/
个人邮箱:kecilimu@163.com
转载请务必注明出处
文章主图是陌芋大大的图