Is it possible to plot implicit 3d equation using sympy?
Asked Answered
C

1

8

Is there a way to plot a 3 variable implicit equation using sympy. Going by docs it has only support for implicit 2d plots. Or are there any other options for plotting a 3d plot using python where the equation can be an input from user

Cacilie answered 14/3, 2015 at 22:8 Comment(3)
What about using a contour plot with mayavi? You just need to provide a meshgrid for $(x,y,z)$ and your function $f(x,y,z)=0$. After that, tell that just show surfaces for the value of zero.Whereon
@Whereon Yeah nice idea...but plotting only those with values of 0 can be difficult I guess.... as the probability of having 0 can be less and completely depends on the functionCacilie
No, your function always can be re-written as $f(x,y,z)=0$, so, the values in the right hand side that you are interested in are 0. I will give some examples as an answer.Whereon
W
12

I am turning my comment into an answer. I suggest to use mayavi and contour3d for this task. You can always rewrite your implicit function to be f(x,y,z)=0. For a sphere we have x^2 + y^2 + z^2 = r^2, that can be rewritten as f(x,y,z) = x^2 + y^2 + z^2 - r^2 = 0.

Below, some examples

import numpy as np
from mayavi import mlab

mlab.clf()
x, y, z = np.mgrid[-3:3:50j, -3:3:50j, -3:3:50j]

# Plot a sphere of radius 1
values = x*x + y*y + z*z - np.sqrt(3)
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()

# Plot a torus
R = 2
r = 1
values = (R - np.sqrt(x**2 + y**2))**2 + z**2 - r**2
mlab.figure()
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()

# Plot a Scherk's second surface
x, y, z = np.mgrid[-4:4:100j, -4:4:100j, -8:8:100j]
values = np.sin(z) - np.sinh(x)*np.sinh(y)
mlab.figure()
mlab.contour3d(x, y, z, values, contours=[0])
mlab.axes()
mlab.show()

That gives as results

Sphere: Sphere plotted with Mayavi

Torus: Torus plotted with Mayavi

Scherk's second surface: Scherk's second surface plotted with Mayavi

Whereon answered 15/3, 2015 at 6:40 Comment(2)
Very nice post (upvoted). Q: I wonder how to modify this to plot the intersection of such surfaces: say F(x, y, z) = 0 and G(x, y, z) = 0. Thanks in adance!Renovate
@dohmatob, if you refer to the region enclosed by two implicit functions you can use max(F, G). If you refer to the curve where the two functions intersect, I don´t know. But I think that would be a good question for Computational Science Stack Exchange.Whereon

© 2022 - 2024 — McMap. All rights reserved.