Trying to plot multivariate function in 3D matplotlib; returns empty figure

倖福魔咒の 提交于 2020-01-05 05:48:06

问题


I am trying to plot a function F(x1,x2) in 3D matplotlib, follwoing a tutorial from here: http://glowingpython.blogspot.com/2012/01/how-to-plot-two-variable-functions-with.html

Once I try to run the code, the figure turns out to be empty, not even the axes output is seen. I was wondering if anyone could figure out the resaon behind this behavior. I am using python 2.7

from __future__ import division

from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import math 
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from matplotlib import pylab
from numpy import arange,array,ones
from scipy import stats
import numpy
import matplotlib.ticker as mtick
import sys
import os


# the function that I'm going to plot
def z_func(x1,x2):
 return exp(-(1-x1)**2 - 100*((x2-x1**2)**2))


x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)
X1,X2 = meshgrid(x1, x2) # grid of point
Z = z_func(X1, X2) # evaluation of the function on the grid


fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X1, X2, Z, rstride=1, cstride=1, cmap=cm.RdBu,linewidth=0, antialiased=False)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
ax.view_init(elev=25, azim=-120)

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

回答1:


Your code works for me. I just needed to wait till the computer will finish the computation. The long computation is because of the size of x1 and x2. Try to change these lines:

x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)

to the following lines:

x1 = arange(5.0,-5.0,-0.1)
x2 = arange(-5.0,5.0,0.1)

p.s. I advise you to arrange your imports. You only need the following:

from numpy import exp, arange
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from pylab import meshgrid
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm


来源:https://stackoverflow.com/questions/39881812/trying-to-plot-multivariate-function-in-3d-matplotlib-returns-empty-figure

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