piecewise function with 3d plot

送分小仙女□ 提交于 2019-12-11 19:58:48

问题


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

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