问题
I am having trouble getting np.piecewise
to work for multiple dimensional plotting due to broadcast errors.
Does anyone have any manner to get around this?
Here is what I have in a simplified executable script:
import numpy as np
from pylab import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
num_steps = 100
x_arr = np.linspace(0,100, num_steps)
y_arr = np.linspace(0,20, num_steps)
def zfunc(x, y):
return np.piecewise(x, [x>=500, x<500], [x, -x])
x,y = np.meshgrid(x_arr, y_arr)
z =zfunc(x,y)
fig=plt.figure()
ax=fig.subplot(1,1,1,projection='3d')
p = x.plot_surface(x,y,z,rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0,antialiased=False)
plt.show()
Which gives the error:
return np.piecewise(x, [x>=500, x<500], [x, -x])
File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 716, in piecewise
y[condlist[k]] = item
ValueError: array is not broadcastable to correct shape
回答1:
Taking a look at the docstring of the function you're using is usually a good idea. I found this solution there.
np.piecewise(x, [x>=500, x<500], [lambda x: x, lambda x: -x])
funclist : list of callables, f(x,args,*kw), or scalars Each function is evaluated over
x
wherever its corresponding condition is True. It should take an array as input and give an array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar
) is assumed.
来源:https://stackoverflow.com/questions/22430429/piecewise-function-with-3d-plot