如何解决如何在 Matplotlib 中围绕任意轴旋转 3-D 图
我正在尝试旋转在 Matplotlib 中生成的 3D 体素图。具体来说,在保持坐标系不变的同时,我想将图像围绕 x 轴旋转 180 度。这是 Matplotlib 文档中的一个示例,以及我想通过我的绘图获得的转换的可视化:
作为参考,这里是生成初始体素图的代码(同样来自 Matplotlib 文档):
import matplotlib.pyplot as plt
import numpy as np
def explode(data):
size = np.array(data.shape)*2
data_e = np.zeros(size - 1,dtype=data.dtype)
data_e[::2,::2,::2] = data
return data_e
# build up the numpy logo
n_voxels = np.zeros((4,3,4),dtype=bool)
n_voxels[0,:] = True
n_voxels[-1,:] = True
n_voxels[1,2] = True
n_voxels[2,1] = True
facecolors = np.where(n_voxels,'#FFD65DC0','#7A88CCC0')
edgecolors = np.where(n_voxels,'#BFAB6E','#7D84A6')
filled = np.ones(n_voxels.shape)
# upscale the above voxel image,leaving gaps
filled_2 = explode(filled)
fcolors_2 = explode(facecolors)
ecolors_2 = explode(edgecolors)
# Shrink the gaps
x,y,z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2
x[0::2,:,:] += 0.05
y[:,0::2,:] += 0.05
z[:,0::2] += 0.05
x[1::2,:] += 0.95
y[:,1::2,:] += 0.95
z[:,1::2] += 0.95
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x,z,filled_2,facecolors=fcolors_2,edgecolors=ecolors_2)
plt.show()
对于初学者,我尝试翻转 x 坐标(使用 np.flip(x)
作为 x 坐标的输入;但是,这会扭曲光源,并且不会产生所需的结果。有关如何进行的任何输入感谢您完成此轮换。
解决方法
试试这个代码
将 matplotlib.pyplot 导入为 plt 将 numpy 导入为 np
def explode(data):
size = np.array(data.shape)*2
data_e = np.zeros(size - 1,dtype=data.dtype)
data_e[::2,::2,::2] = data
return data_e
# build up the numpy logo
n_voxels = np.zeros((4,3,4),dtype=bool)
n_voxels[0,:] = True
n_voxels[-1,:] = True
n_voxels[1,2] = True
n_voxels[2,1] = True
facecolors = np.where(n_voxels,'#FFD65DC0','#7A88CCC0')
edgecolors = np.where(n_voxels,'#BFAB6E','#7D84A6')
filled = np.ones(n_voxels.shape)
# upscale the above voxel image,leaving gaps
filled_2 = explode(filled)
fcolors_2 = explode(facecolors)
ecolors_2 = explode(edgecolors)
# Shrink the gaps
x,y,z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2
x[0::2,:,:] += 0.05
y[:,0::2,:] += 0.05
z[:,0::2] += 0.05
x[1::2,:] += 0.95
y[:,1::2,:] += 0.95
z[:,1::2] += 0.95
import matplotlib.pyplot as plt
import numpy as np
def explode(data):
size = np.array(data.shape)*2
data_e = np.zeros(size - 1,1::2] += 0.95
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x,z,filled_2,facecolors=fcolors_2,edgecolors=ecolors_2)
for angle in range(0,360):
ax.view_init(30,angle)
plt.draw()
plt.pause(.001)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。