Search code examples
pythonmatplotlibdata-visualizationmayavi

Plotting function of 3 dimensions over given domain with matplotlib


I am trying to visualize a function of 3 parameters over a cube in R^3 to get an idea of the smoothness of the function. An example of this problem is shown in the sample code below

%pylab
from mpl_toolkits.mplot3d import Axes3D
import itertools

x = np.linspace(0,10,50)
y = np.linspace(0,15,50)
z = np.linspace(0,8,50)

points = []
for element in itertools.product(x, y, z):
    points.append(element)

def f(vals):
    return np.cos(vals[0]) + np.sin(vals[1]) + vals[2]**0.5

fxyz = map(f, points)
xi, yi, zi = zip(*points)

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xi, yi, zi, c=fxyz, alpha=0.5)
plt.show()

cube

The problem with this approach is that the inside of the cube cannot be visualized. Is there a better way to graph a function over some dense subset of R^3?


Solution

  • As @HYRY and @nicoguaro suggested in the comments above, Mayavi is much better suited for this type of work. There is a good set of examples here that I used for reference. Here is what I came up with

    import numpy as np
    from mayavi import mlab
    
    x = np.linspace(0,10,50)
    y = np.linspace(0,15,50)
    z = np.linspace(0,8,50)
    
    X, Y, Z = np.meshgrid(x, y, z)
    
    s = np.cos(X) + np.sin(Y) + Z**0.5
    b1 = np.percentile(s, 20)
    b2 = np.percentile(s, 80)
    mlab.pipeline.volume(mlab.pipeline.scalar_field(s), vmin=b1, vmax=b2)
    mlab.axes()
    mlab.show()
    

    After which I rotated the figure to desired angles with the GUI and saved desired views

    angle1 angle2