用Matplotlib不代表半个像素

问题描述

有人知道是否可能无法使用plt.imshow()来表示对角矩阵的一半像素吗?

以图形方式表示我要寻找的内容

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib

bins = 5
Z = np.random.rand(bins,bins)

# Select lower triangle values:
condition = np.tril(np.ones((Z.shape))).astype(np.bool)
Z = np.where(condition,Z,np.nan)

fig,ax = plt.subplots(figsize = (8,8))
ax.imshow(Z,cmap = 'Spectral')

我想这可以通过用遮罩覆盖图像来完成,但是我宁愿避免

解决方法

您可以将Patch对象用作matplotlib中的剪贴蒙版。参见https://matplotlib.org/3.1.0/gallery/images_contours_and_fields/image_clip_path.html

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib

bins = 5
Z = np.random.rand(bins,bins)

# Select lower triangle values:
condition = np.tril(np.ones((Z.shape))).astype(np.bool)
Z = np.where(condition,Z,np.nan)

fig,ax = plt.subplots()
im = ax.imshow(Z,cmap = 'Spectral')

tri = matplotlib.patches.Polygon([(0,0),(1,(0,1)],closed=True,transform=ax.transAxes)
im.set_clip_path(tri)

enter image description here