0

The issue is that this script is not able to plot a sphere for example while it is able to plot several cones such as the one in the script.

I have changes the shape and tried finding the lines from which the error comes from using the error message given when plotting a sphere.

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()

The result with a sphere function is that the script crashes. I would hope this script should be able to graph this kind of 3D shapes.

Billy Case
  • 27
  • 10

1 Answers1

1

Is this the error you are getting by any chance?

TypeError: can't convert complex to float

The way this is formulated you are asking for an imaginary number back. If you define this as your sphere equation:

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

you will end up asking for sqrt(-1) when x=y=0, which will not work. Try parameterizing with spherical coordinates like in this example: Python/matplotlib : plotting a 3d cube, a sphere and a vector?