首页 > 解决方案 > 用 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')

我想这可以通过用蒙版覆盖图像来完成,但这是我宁愿避免的选项。

标签: pythonmatplotlibimshow

解决方案


您可以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),(0,1)], closed=True, transform=ax.transAxes)
im.set_clip_path(tri)

在此处输入图像描述


推荐阅读