7

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
  • 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. – nicoguaro Mar 15 '15 at 05:49
  • @nicoguaro 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 function – Srinath Mandava Mar 15 '15 at 06:09
  • 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. – nicoguaro Mar 15 '15 at 06:37

1 Answers1

11

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

nicoguaro
  • 3,629
  • 1
  • 32
  • 57
  • 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! – dohmatob Nov 10 '18 at 22:57
  • @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. – nicoguaro Nov 11 '18 at 23:08