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

Iva*_*lin 1 python matplotlib

我在 Python 中使用 matplotlib 创建了一个 2D 绘图,一个例子是:一些点的二维图 它是使用 2 个列表生成的:

import matplotlib.pyplot as plt
import numpy as np

plt.plot(X, Y) #X and Y are lists, containing the x and y coordinates of points respectively
plt.show()
Run Code Online (Sandbox Code Playgroud)

现在我想围绕 Y 轴创建该图的旋转,并以 Y 轴垂直的方式将其可视化。使用 matplotlib 如何做到这一点?

Wil*_*ler 6

如果您有一条曲线定义为两个一维数组中x和点的集合,并且您希望将它们绕轴旋转,您只需构造二维数组即可满足 matplotlib 的要求,方法是使用、 of with和for获取外积在 [0, 2\xcf\x80] 中。这将为您提供空间中笛卡尔点的集合,这些点将表示通过绕轴旋转每个原始点而创建的圆。由于 的预期,构造数组有点棘手。yyAxes3D.plot_surfacenp.outer()xnp.cos(theta)np.sin(theta)thetaxyzzshapeplot_surface()

\n

这是一个完整的示例,演示了此方法并将其与原始二维图进行比较

\n
from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn = 100\n\nfig = plt.figure(figsize=(12,6))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122,projection=\'3d\')\ny = np.linspace(np.pi/8, np.pi*4/5, n)\nx = np.sin(y)\nt = np.linspace(0, np.pi*2, n)\n\nxn = np.outer(x, np.cos(t))\nyn = np.outer(x, np.sin(t))\nzn = np.zeros_like(xn)\n\nfor i in range(len(x)):\n    zn[i:i+1,:] = np.full_like(zn[0,:], y[i])\n\nax1.plot(x, y)\nax2.plot_surface(xn, yn, zn)\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n