matplotlib Plot Imshow on a Torus(lattice with PBC)(在圆环上绘制Imshow图)

vsikbqxv  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(108)

matplotlib或其他Python软件包中是否有任何“简单”的解决方案来在2D环面上绘制正方形晶格(也称为具有周期性边界条件的晶格)?
假设我有一个简单的2D数组

# ...
a = np.random.random((50, 50))
plt.imshow(a)

我想把这个平面 Package 成一个环面,这可以通过以下方式实现:

from mpl_toolkits.mplot3d import Axes3D
# Generating Torus Mesh
angle = np.linspace(0, 2 * np.pi, 100)
theta, phi = np.meshgrid(angle, angle)
r, R = .25, 1.
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)
Z = r * np.sin(phi)

fig = plt.figure()
ax = fig.add_subplot(projection = '3d')

ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(-1, 1)
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1)

plt.show()

我考虑过将XY的值编码到一个colormap中,传递给plot_surface的选项cmap,colormap应该根据数组a的内容包含图像的每种颜色。
有什么想法?

webghufk

webghufk1#

首先,让我们介绍地板功能。

thetaphi0“连续”增加到2*pi。我们可以将它们缩放到矩阵a的维度,并使用floor函数的属性来计算索引并从矩阵中提取适当的颜色。
代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import matplotlib

# random colors
theta_dim, phi_dim = 100, 30
a = np.random.random((theta_dim, phi_dim))

# Generating Torus Mesh
angle = np.linspace(0, 2 * np.pi, 100)
theta, phi = np.meshgrid(angle, angle)
r, R = .25, 1.
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)
Z = r * np.sin(phi)

# compute the indexes
t, p = [var / (2 * np.pi) for var in [theta, phi]]
t = np.floor((t - 0.5) * a.shape[0]).astype(int) + 1
p = np.floor((p - 0.5) * a.shape[1]).astype(int) + 1
# extract the color value from the matrix
colors = a[t, p]
# apply a colormap to the normalized color values
norm = Normalize(vmin=colors.min(), vmax=colors.max())
cmap = matplotlib.colormaps.get_cmap("viridis")
normalized_colors = cmap(norm(colors))

fig = plt.figure()
ax = fig.add_subplot(projection = '3d')
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, facecolors=normalized_colors)
ax.set_aspect("equal")
plt.show()

相关问题