具有3d图的分段函数 [英] piecewise function with 3d plot

查看:154
本文介绍了具有3d图的分段函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于广播错误,我无法让np.piecewise用于多维绘图.

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

哪个出现错误:

 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

推荐答案

通常来看一下使用的函数的文档字符串.我在那里找到了这个解决方案.

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:可调用对象,f(x, args, * kw)或标量的列表 每个函数在x上的任何位置进行评估 条件为真.它应该以数组作为输入并给出一个数组 或标量值作为输出.如果不是可调用的, 提供标量,则常数函数(lambda x: scalar)为

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.

这篇关于具有3d图的分段函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆