如何添加另一个子图以向 x 轴显示革命固体?

How to Add another subplot to show Solid of Revolution toward x-axis?

提问人:Freya the Goddess 提问时间:12/31/2022 最后编辑:コリンFreya the Goddess 更新时间:1/1/2023 访问量:69

问:

我从此处的主题修改了此代码:

如何在 Python 中使用 matplotlib 生成 2D 绘图的革命

该图包含 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()
python numpy matplotlib

评论


答:

2赞 コリン 1/1/2023 #1

选项 1:

只需反转并切换功能轴即可。xy

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

选项 2:

这有点复杂。您也可以通过查找原始函数的逆函数来实现此目的。

的反之亦然。f(x) = y = x^3 + 2f^{-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()

enter image description here

enter image description here

评论

0赞 Freya the Goddess 1/1/2023
太棒了!Arigato Gozaimasu