rotate a matrix using matplotlib

Instead of changing the origin of the skew transformation, you could chain it with a translation in the x direction to achieve the transformation you are looking for.

Note that the skew transform takes an angle in radians (you were using it with degrees). There is an equivalent skew_deg transform if you want to work in degrees, but here I just work in radians.

Note also that I think you want to have an isosceles triangle with base and height both equal to 20 (or whatever you choose N to be), the angle you want is not 30 degrees, but actually arctan(1/2) (=26.56deg).

The amount you need to translate in the x direction is xtrans = N * np.tan(angle).

You can chain transforms easily in matplotlib. Here we can skew first, then translate:

mtransforms.Affine2D().skew(-angle, 0).translate(xtrans, 0)

Note that this script works for any value of N.

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

N = 20
matrix = np.random.rand(N, N)

# Generate a boolean matrix (same shape than 'matrix') and select lower triangle values:

condition = np.tril(np.ones((matrix.shape))).astype(np.bool)
triangle = np.where(condition, matrix, np.nan)

fig, ax = plt.subplots(figsize = (8,8))

im = ax.imshow(triangle, cmap = 'Spectral')

angle = np.arctan(1/2)
xtrans = N * np.tan(angle)
im.set_transform(mtransforms.Affine2D().skew(-angle, 0).translate(xtrans, 0) + ax.transData)

ax.set_xlim(-0.5, N + 0.5)

For N = 20 enter image description here

And for N = 30 enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top