如何在 matplotlib 中旋转 3D 表面 [英] how to rotate a 3D surface in matplotlib

查看:80
本文介绍了如何在 matplotlib 中旋转 3D 表面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写代码在matplotlib中绘制抛物面的3D表面.

I have written code to plot a 3D surface of a parabaloid in matplotlib.

我将如何旋转图形,以便图形保持在原处(即没有垂直或水平移动),但是它绕y = 0和z = 0线绕theta角度旋转(我已突出显示了围绕该线该图应以绿色旋转).这是一个插图,可帮助形象化我所描述的内容:

How would I rotate the figure so that the figure remains in place (i.e. no vertical or horizontal shifts) however it rotates around the line y = 0 and z = 0 through an angle of theta ( I have highlighted the line about which the figure should rotate in green). Here is an illustration to help visualize what I am describing:

例如,如果将图形绕直线旋转180度,则将导致图形上下颠倒",因此原点处的点将成为最大点.

For example, If the figure were rotated about the line through an angle of 180 degrees then this would result in the figure being flipped 'upside down' so that the point at the origin would be now be the maximum point.

我还想旋转轴,以便保持色彩图.这是绘制图形的代码:

I would also like to rotate the axis so that the colormap is maintained. Here is the code for drawing the figure:

#parabaloid
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

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

#creating grid
y = np.linspace(-1,1,1000)
x = np.linspace(-1,1,1000)
x,y = np.meshgrid(x,y)

#set z values
z = x**2+y**2

#label axes
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


#plot figure
ax.plot_surface(x,y,z,linewidth=0, antialiased=False, shade = True, alpha = 0.5)

plt.show()

推荐答案

我的评论如下:

import mayavi.mlab as mlab
import numpy as np
x,y = np.mgrid[-1:1:0.001, -1:1:0.001]
z = x**2+y**2
s = mlab.mesh(x, y, z)
alpha = 30  # degrees
mlab.view(azimuth=0, elevation=90, roll=-90+alpha)

mlab.show()

或关注@Tamas答案:

or following @Tamas answer:

#parabaloid
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from math import sin, cos, pi
import matplotlib.cm as cm

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

#creating grid
y = np.linspace(-1,1,200)
x = np.linspace(-1,1,200)
x,y = np.meshgrid(x,y)

#set z values
z0 = x**2+y**2

# rotate the samples by pi / 4 radians around y
a = pi / 4
t = np.transpose(np.array([x,y,z0]), (1,2,0))
m = [[cos(a), 0, sin(a)],[0,1,0],[-sin(a), 0, cos(a)]]
x,y,z = np.transpose(np.dot(t, m), (2,0,1))
# or `np.dot(t, m)` instead `t @ m`


#label axes
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

#plot figure
ax.plot_surface(x,y,z,linewidth=0, antialiased=False, shade = True, alpha = 0.5, facecolors=cm.viridis(z0))

plt.show()

这篇关于如何在 matplotlib 中旋转 3D 表面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆