numpy 如何添加另一个子图来显示旋转体朝向x轴?

5us2dqdw  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(104)

我有这个代码修改的主题在这里:
How to produce a revolution of a 2D plot with matplotlib in Python
该图包含XY平面中的一个子图和旋转实体朝向y轴的另一个子图。
我想添加另一个子图,它是向x轴旋转的实体+如何向每个子图(在它们上面)添加图例,因此将有3个子图。
这是我的MWE:

# Compare the plot at xy axis with the solid of revolution
# For function x=(y-2)^(1/3)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

n = 100

fig = plt.figure(figsize=(12,6))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122,projection='3d')
y = np.linspace(np.pi/8, np.pi*40/5, n)
x = (y-2)**(1/3) # x = np.sin(y)
t = np.linspace(0, np.pi*2, n)

xn = np.outer(x, np.cos(t))
yn = np.outer(x, np.sin(t))
zn = np.zeros_like(xn)

for i in range(len(x)):
    zn[i:i+1,:] = np.full_like(zn[0,:], y[i])

ax1.plot(x, y)
ax2.plot_surface(xn, yn, zn)
plt.show()
h9a6wy2h

h9a6wy2h1#

选项1:

只需颠倒xy即可切换函数的轴。

x = np.linspace(np.pi/8, np.pi*40/5, n)
y = (x-2)**(1/3)
选项2:

这个过程有点复杂,你也可以通过求原函数的反函数来完成。
f(x) = y = x^3 + 2的倒数是f^{-1}(y) = (y - 2)^(1/3)
我修改了你提供的代码。

import matplotlib.pyplot as plt
import numpy as np

n = 100

fig = plt.figure(figsize=(14, 7))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222, projection='3d')
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224, projection='3d')
y = np.linspace(np.pi / 8, np.pi * 40 / 5, n)
x = (y - 2) ** (1 / 3)
t = np.linspace(0, np.pi * 2, n)

xn = np.outer(x, np.cos(t))
yn = np.outer(x, np.sin(t))
zn = np.zeros_like(xn)
for i in range(len(x)):
    zn[i:i + 1, :] = np.full_like(zn[0, :], y[i])

ax1.plot(x, y)
ax1.set_title("$f(x)$")
ax2.plot_surface(xn, yn, zn)
ax2.set_title("$f(x)$: Revolution around $y$")

# find the inverse of the function
x_inverse = y
y_inverse = np.power(x_inverse - 2, 1 / 3)
xn_inverse = np.outer(x_inverse, np.cos(t))
yn_inverse = np.outer(x_inverse, np.sin(t))
zn_inverse = np.zeros_like(xn_inverse)
for i in range(len(x_inverse)):
    zn_inverse[i:i + 1, :] = np.full_like(zn_inverse[0, :], y_inverse[i])

ax3.plot(x_inverse, y_inverse)
ax3.set_title("Inverse of $f(x)$")
ax4.plot_surface(xn_inverse, yn_inverse, zn_inverse)
ax4.set_title("$f(x)$: Revolution around $x$")

plt.tight_layout()
plt.show()

相关问题