如何在 Matplotlib 中围绕任意轴旋转 3-D 图

问题描述

我正在尝试旋转在 Matplotlib 中生成的 3D 体素图。具体来说,在保持坐标系不变的同时,我想将图像围绕 x 轴旋转 180 度。这是 Matplotlib 文档中的一个示例,以及我想通过我的绘图获得的转换的可视化:

A visualization of rotation about the X-axis

作为参考,这里是生成初始体素图的代码(同样来自 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()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...