python - 使用 matplotlib 绘制分段函数会导致 ValueError : The truth value of an array with more than one element is ambiguous

标签 python numpy matplotlib

我想使用 matplotlib 绘制分段函数:

import numpy as np
import matplotlib.pyplot as plt

def pwf(x):
    return 0 if x < 0 else 1
x = np.linspace(-1, 1, 100)
plt.plot(x, pwf(x))

我收到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

但是,在使用 (x < 0).any() 时,我只是得到 True ,在 (x < 0).all() 上我得到 False ,这两者都不适合我的情况。

我在这里找到了答案: Python Error: Using matplotlib: Truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ,但是问题和答案都充满了不必要的代码,因此我决定发布一个简洁的解决方案。

最佳答案

您可以使用

def pwf(x):
    return (x < 0).astype(float)

或者,对于适用于 0 和 1 以外的数字的解决方案,

def pwf(x):
    return np.array([1,0])[(x < 0).astype(int)]

此类问题的一般解决方案是将函数向量化:

import matplotlib.pyplot as plt
import numpy as np

def pwf(x):
    return 0 if x < 0 else 1

x = np.linspace(-1, 1, 100)

plt.plot(x, np.vectorize(pwf)(x))
plt.show()

关于python - 使用 matplotlib 绘制分段函数会导致 ValueError : The truth value of an array with more than one element is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59673987/

相关文章:

python - 在 Python 中以特定参数值查询 3D 样条曲线上的点

python - 在 Python 中绘制 Networkx 图

python - 在 python 中做散点图时标记数据

python - 根据条件和年份标记 NaN 值

python - 向量外积的泛化 : apply it to every column of a matrix

python - matplotlib 日志轴 : display powers of 10 only

python - 从凸图像蒙版的边界提取平均颜色

python - Keras: ValueError: Input 0 is incompatible layer 问题

python - 在 Python 中过滤字典......再次

python - 抓取带有交互式按钮的网站