[英]Rotate a matrix with Matplotlib
我30度向右使用Matplotlib的转化方法旋转anxn矩阵(N = 20,虽然它可以变化)。
出现错误是因为旋转是从顶部而不是从底部执行的。 我试图通过np.flip()
或ax.imshow(origin = 'lower')
反转索引,但它也反转三角形,所以我需要发现如何设置转换原点。
Defintley,这就是我想获得的:
请注意,符合对角矩阵的小方块将变成三角形。 这能做到吗? 也许通过返回半个像素的 imshow 方法? 其余的像素将保持不变(变形的小方块)。
这是生成矩阵的代码(起点):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
matrix = np.random.rand(20,20)
# 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))
ax.imshow(triangle, cmap = 'Spectral')
这是尝试旋转它的代码:
im = ax.imshow(matrix, cmap = 'Spectral')
im.set_transform(mtransforms.Affine2D().skew(30, 0) + ax.transData)
ax.plot(transform = trans_data)
我没有使用 Matplotlib 的 Triangle 类,因为三元图是通过插值操作表示的,我想表示原始矩阵值。
我真的很感激有人的帮助。 非常感谢您提前。
您可以将其与 x 方向的平移链接起来,而不是更改倾斜变换的原点,以实现您正在寻找的变换。
请注意, skew
变换采用以弧度表示的角度(您使用的是度数)。 如果你想以度为单位工作,有一个等效的skew_deg
变换,但在这里我只以弧度工作。
还要注意,我认为你想要一个等腰三角形,底和高都等于 20(或者你选择 N 的任何值),你想要的角度不是 30 度,而是实际上 arctan(1/2) (=26.56度)。
您需要在 x 方向平移的量是xtrans = N * np.tan(angle)
。
您可以在 matplotlib 中轻松链接变换。 这里我们可以先倾斜,再翻译:
mtransforms.Affine2D().skew(-angle, 0).translate(xtrans, 0)
请注意,此脚本适用于任何 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)
plt.show()
我终于得到了一个等边三角形缩放 y 轴。这里我展示了代码。
因此,它允许将矩阵转换为等边三角形,这回答了我之前的问题:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib
bins = 50
Z = np.random.rand(bins, bins)
# Generate a boolean matrix (same shape than 'matrix') and 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))
im = ax.imshow(Z, cmap = 'Spectral')
# Required angles (in Rad)
alpha = np.arctan(1/2) # 26 deg angle, in radians.
beta = np.arctan(np.pi/6) # 30 deg angle, in radians.
# Coefficients:
xtrans = np.sin(beta) * bins
scale_y = np.cos(beta)
# Transformation:
im.set_transform(mtransforms.Affine2D().skew (-alpha, 0)
.scale (1,scale_y)
.translate (xtrans, 0)
+ ax.transData)
ax.set_ylim(bins,-5)
ax.set_xlim(-5,bins)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.