散点图(matplotlib)(python)的关键错误

2024-09-27 00:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框

    artist  bpm nrgy    dnce    dB  live    spch    val acous
20  drake   112.0   26.0    49.0    -17.0   7.0 9.0 31.0    65.0
35  drake   100.0   41.0    77.0    -7.0    7.0 10.0    29.0    0.0
36  drake   152.0   57.0    64.0    -7.0    9.0 11.0    43.0    37.0
37  drake   122.0   52.0    63.0    -10.0   9.0 27.0    30.0    3.0
47  drake   172.0   57.0    75.0    -8.0    53.0    48.0    55.0    38.0
48  drake   100.0   24.0    70.0    -9.0    11.0    5.0 38.0    62.0

我试图创建一个散点图,但我总是遇到钥匙的问题。请帮忙,谢谢

    fig = plt.figure(figsize=(12, 18))

current = 1
for col in columns:
    plt.subplot(5, 2, current) # 5 rows, 2 histograms per row
    current += 1 # looping over to the next measure
    plt.plot(df_artist.index, df_artist[col], data=df_artist, linestyle='none', marker='o') 
    plt.title(col)

plt.show()

我一直得到一个关键错误和一个空的绘图:(

谢谢大家!


Tags: 数据livedfdbartistpltcolval
1条回答
网友
1楼 · 发布于 2024-09-27 00:16:09

假设您想要使用plot(而不是直方图)的散点图

你的代码必须是这样的

fig = plt.figure(figsize=(12, 18))

current = 1
for col in df.columns:
    plt.subplot(5, 2, current) # 5 rows, 2 histograms per row
    current += 1 # looping over to the next measure
    df_x = np.array(df.index)
    df_y = np.array(df[col])
    plt.plot(df_x, df_y, linestyle='none', marker='o') 
    plt.title(col)

plt.show()

为什么您的代码不工作?

出现键错误的原因是df.index是一个可变的列表,不能对可变对象进行散列。因此,您得到了错误

为什么新代码有效?

我只是将值列表转换为numpy数组,该数组包含int/str值,因此不可变。因此,它接受要绘制的值

输出

enter image description here

enter image description here

相关问题 更多 >

    热门问题