gpt4 book ai didi

Python:如何绕 z 轴旋转曲面并绘制 3d 图?

转载 作者:行者123 更新时间:2023-12-01 04:05:58 27 4
gpt4 key购买 nike

我想要获得如下所示的 2d 和 3d 绘图。
给出了曲线方程。
我们如何在 python 中做到这一点?
我知道可能有重复,但在发布时我找不到任何有用的帖子。

我最初的尝试是这样的:

# Imports
import numpy as np
import matplotlib.pyplot as plt


# to plot the surface rho = b*cosh(z/b) with rho^2 = r^2 + b^2
z = np.arange(-3, 3, 0.01)
rho = np.cosh(z) # take constant b = 1

plt.plot(rho,z)
plt.show()

一些相关链接如下:
Rotate around z-axis only in plotly

3d 绘图应如下所示:
enter image description here

最佳答案

好吧,我认为您实际上是在要求绕轴旋转二维曲线以创建曲面。我有 CAD 背景,所以这就是我解释事情的方式。我并不是最擅长数学,所以请原谅任何笨拙的术语。不幸的是,您必须完成其余的数学运算才能获得网格的所有点。

这是您的代码:

#import for 3d
from mpl_toolkits.mplot3d import Axes3D

import numpy as np
import matplotlib.pyplot as plt

将 arange 更改为捕获端点的 linspace,否则 arange 将丢失数组末尾的 3.0:

z = np.linspace(-3, 3, 600)
rho = np.cosh(z) # take constant b = 1

由于 rho 是每个 z 高度的半径,我们需要计算该半径周围的 x,y 点。在此之前,我们必须弄清楚在该半径上的哪些位置可以获得 x,y 坐标:

#steps around circle from 0 to 2*pi(360degrees)
#reshape at the end is to be able to use np.dot properly
revolve_steps = np.linspace(0, np.pi*2, 600).reshape(1,600)

获取圆周围点的三角函数是:
x = r*cos(theta)
y = r*sin(theta)

对于你来说,r 是你的 rho,theta 是 revolve_steps

通过使用 np.dot 进行矩阵乘法,您将得到一个二维数组,其中 x 和 y 的行将对应于 z 的行

theta = revolve_steps
#convert rho to a column vector
rho_column = rho.reshape(600,1)
x = rho_column.dot(np.cos(theta))
y = rho_column.dot(np.sin(theta))
# expand z into a 2d array that matches dimensions of x and y arrays..
# i used np.meshgrid
zs, rs = np.meshgrid(z, rho)

#plotting
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
fig.tight_layout(pad = 0.0)
#transpose zs or you get a helix not a revolve.
# you could add rstride = int or cstride = int kwargs to control the mesh density
ax.plot_surface(x, y, zs.T, color = 'white', shade = False)
#view orientation
ax.elev = 30 #30 degrees for a typical isometric view
ax.azim = 30
#turn off the axes to closely mimic picture in original question
ax.set_axis_off()
plt.show()

#ps 600x600x600 pts takes a bit of time to render

我不确定它是否已在最新版本的 matplotlib 中修复,但设置 3d 绘图的纵横比:

ax.set_aspect('equal')

效果不太好。您可以在 this stack overflow question 找到解决方案

关于Python:如何绕 z 轴旋转曲面并绘制 3d 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35592250/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com