首页 > 解决方案 > 散点图的关键错误(matplotlib)(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()

我不断收到一个关键错误和一个空的情节:(

谢谢!

标签: pythonpandasdataframematplotlibscatter-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 值,因此不可变。因此它接受要绘制的值

输出

在此处输入图像描述

在此处输入图像描述


推荐阅读