首页 > 解决方案 > 只有大小为 1 的数组可以转换为 Python 标量图形 sin

问题描述

我想在同一个图中绘制多个方程。我遇到了这个问题

def data():
    #func 1 - noisy sin wave
    x = np.linspace(1, 10000)
    func1 = 100*(np.sin(x/1000*2*np.pi*5) + np.random.normal(scale=0.1, size=len(x)))
    ...

data我在一个具有返回线的函数中定义了所有方程

return np.array([func1, fun2, func3])

然后我使用

plt.plot(data().T)

但是 func1 给出了错误:

only size-1 arrays can be converted to Python scalars

我怎样才能解决这个问题?

标签: pythonpython-3.xnumpy

解决方案


我怀疑问题是你的函数输出不同长度的数组。当长度相同时它对我有用,但如果它们不同,您将不会收到消息

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray

我会做类似的事情

function_data = data()
for data in function_data:
    plt.plot(data.T)

我还将使用列表而不是数组作为函数的输出,因为不推荐使用具有不同大小的列或行的 numpy 数组,正如错误消息指出的那样。Numpy 数组很棒,但数组列表在这种情况下很有用。


推荐阅读