Không thể hiện nửa pixel với Matplotlib

Oct 30 2020

Có ai biết nếu nó có thể không đại diện cho một nửa số pixel của ma trận đường chéo bằng cách sử dụng plt.imshow()không?

Điều này được thể hiện bằng đồ thị những gì tôi đang tìm kiếm:

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')

Tôi đoán điều này có thể được thực hiện bằng cách che hình ảnh bằng một chiếc mặt nạ , nhưng đó là một lựa chọn mà tôi muốn tránh .

Trả lời

2 DizietAsahi Oct 30 2020 at 22:06

Bạn có thể sử dụng một Patchđối tượng làm mặt nạ cắt trong matplotlib. Xemhttps://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)