ValueError:尝试使用matplotlib进行绘制时,使用序列设置数组元素

问题描述 投票:0回答:1

当我尝试运行以下代码时:

from matplotlib import pyplot as plt

Xpos = df[df['bound']==1]
Xneg = df[df['bound']==0]
y1, X1 = Xpos['Id'].values, Xpos['seq'].values
y2, X2 = Xneg['Id'].values, Xneg['seq'].values

fig, ax = plt.subplots()
ax.plot(y1, X1 , label='bounded sequences', color='blue')
ax.plot(y2, X2 , label='unbounded sequences', color='red')
plt.show()

我收到此错误:ValueError: setting an array element with a sequence.df的示例输出类似于您发现的here。有人可以帮忙吗?谢谢。

python arrays matplotlib sequence valueerror
1个回答
0
投票

这里的问题是您试图绘制列表列表。

为了解释您的问题,我创建了一个与您所使用的样本数据集相似的样本数据集(唯一的区别是序列较短)。这是我用来创建数据集的代码:

df_dict = {
    "Id": [0, 1, 2, 3, 4],
    "seq": [[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]],
    "bound": [1, 0, 1, 0, 1]
}
df = pd.DataFrame(df_dict)

如果现在执行代码的第一部分并打印X1变量:

Xpos = df[df['bound']==1]
Xneg = df[df['bound']==0]
y1, X1 = Xpos['Id'].values, Xpos['seq'].values
y2, X2 = Xneg['Id'].values, Xneg['seq'].values
print(X1)

输出将是:

[list([0, 0, 1, 0]) list([0, 0, 1, 0]) list([0, 0, 1, 0])]

如果您向我解释了您要绘制的内容,我们将很乐意为您提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.