ValueError:在尝试使用 matplotlib 绘图时设置带有序列的数组元素



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

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的示例输出与您在此处找到的示例输出类似。
谁能帮忙?
谢谢。

这里的问题是您正在尝试绘制列表列表。

为了向您解释这个问题,我创建了一个类似于您正在使用的示例数据集(唯一的区别是序列更短(。以下是我用于创建数据集的代码:

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

如果您想为 X1 绘制的是每个列表的串联,例如 [

0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],这可能会解决您的问题:
import pandas as pd
from matplotlib import pyplot as plt
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)
Xpos = df[df['bound']==1]
Xneg = df[df['bound']==0]
print(Xpos)
y1, X1 = Xpos['Id'].values, [elem for sub_list in Xpos['seq'].values for elem in sub_list]
y2, X2 = Xneg['Id'].values, [elem for sub_list in Xneg['seq'].values for elem in sub_list]
print(y1)
print(X1)
fig, ax = plt.subplots()
ax.plot(X1, label='bounded sequences', color='blue')
ax.plot(X2, label='unbounded sequences', color='red')
plt.show()

如果你想要散点图而不是线图,你只需要将两个ax.plot函数替换为以下内容:

ax.scatter(range(len(X1)), X1, label='bounded sequences', color='blue')
ax.scatter(range(len(X2)), X2, label='unbounded sequences', color='red')

最新更新