Plotting function of 3 dimensions over given domain with matplotlib

為{幸葍}努か 提交于 2019-12-08 04:14:21

问题


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

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?


回答1:


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



来源:https://stackoverflow.com/questions/27586557/plotting-function-of-3-dimensions-over-given-domain-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!