Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not to represent half a pixel with Matplotlib

Does anybody know if it's possible not to represent half the pixels of the diagonal matrix using plt.imshow()?

This is graphically expressed what I am looking for:

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

I guess this could be done by covering the image with a mask, but it's an option I'd rather avoid.

like image 332
Miguel Gonzalez Avatar asked May 16 '26 15:05

Miguel Gonzalez


1 Answers

You can use a Patch object as a clipping mask in matplotlib. See 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)

enter image description here

like image 147
Diziet Asahi Avatar answered May 19 '26 03:05

Diziet Asahi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!