3D绘图仪仅适用于某些形状

时间:2019-07-03 23:15:24

标签: python-3.x matplotlib

问题是该脚本无法绘制球体,而能够绘制多个圆锥体,例如脚本中的圆锥体。

我已经更改了形状,并尝试使用绘制球体时给出的错误消息来查找错误所在的线。

import sympy as sy
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Plot Figure
nd = 50  # Number of points in graph

ax = plt.axes(projection='3d')  # Adds 3d axis to figure

x1 = np.linspace(-15, 15, nd)
y1 = np.linspace(-15, 15, nd)

X, Y = np.meshgrid(x1, y1)  # Create 2D grid with x1 and y1

i = 0
a = 0
b = 0
Z = np.array([])

x = sy.Symbol('x')
y = sy.Symbol('y')
z = (x**2+y**2)**0.5  # Function goes here

for i in range(nd):  # Iterate over rows
    b = 0
    xv1 = X[a, :]
    yv1 = Y[a, :]
    for i in range(nd):  # Iterate over elements in one row
        xv = xv1[b]
        yv = yv1[b]
        z1 = z.subs([(x, xv), (y, yv)])
        Z = np.append(Z, z1)  # Append values to array just a row
        b = b + 1
    a = a + 1

Z = np.reshape(Z, (nd, nd))

print(Z.dtype)
print(Y.dtype)
print(X.dtype)
Z = Z.astype(float)
Y = Y.astype(float)
X = X.astype(float)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
plt.show()

使用sphere函数的结果是脚本崩溃。我希望该脚本应该能够绘制这种3D形状的图形。

1 个答案:

答案 0 :(得分:0)

这是您偶然遇到的错误吗?

TypeError: can't convert complex to float

以这种方式制定公式时,您需要一个假想的数字。如果您将其定义为球面方程:

z = (x**2+y**2-1)**0.5

当x = y = 0时,您最终会要求sqrt(-1),这将不起作用。尝试使用球形坐标进行参数化,例如以下示例:Python/matplotlib : plotting a 3d cube, a sphere and a vector?