首页 > 解决方案 > 如何从 pandas 数据框创建一个 hexbin 图

问题描述

我有这个数据框:

! curl -O https://raw.githubusercontent.com/msu-cmse-courses/cmse202-S21-student/master/data/Dataset.data

import pandas as pd

#I read it in
data = pd.read_csv("Dataset.data", delimiter=' ', header = None)

#Now I want to add column titles to the file so I add them
data.columns = ['sex','length','diameter','height','whole_weight','shucked_weight','viscera_weight','shell_weight','rings']
print(data)

现在我想获取 x 变量列shell_weight和 y 变量列rings,并使用以下方法将它们绘制为直方图plt.hexbin

df = pd.DataFrame(data)
plt.hexbin(x='shell_weight', y='rings')

出于某种原因,当我绘制代码时它不起作用:

ValueError:第一个参数必须是一个序列

谁能帮我绘制这两个变量的图表?

标签: pythonpandasnumpymatplotlibjupyter

解决方案


ValueError:第一个参数必须是一个序列

问题plt.hexbin(x='shell_weight', y='rings')是 matplotlib 不知道应该是shell_weight什么。除非您指定它,否则rings它不知道。df


由于您已经有一个数据框,因此使用 pandas 绘图是最简单的,但如果您指定源,纯 matplotlib 仍然是可能的df

  • df.plot.hexbin(最简单的)

    在这种情况下,pandas 会自动从 推断列df,所以我们可以只传递列名:

    df.plot.hexbin(x='shell_weight', y='rings') # pandas infers the df source
    
  • plt.hexbin

    使用纯 matplotlib,或者传递实际的列:

    plt.hexbin(x=df.shell_weight, y=df.rings) # actual columns, not column names
    #            ^^^                ^^^
    

    data或者在指定源时传递列名:

    plt.hexbin(x='shell_weight', y='rings', data=df) # column names with df source
    #                                       ^^^^^^^
    


推荐阅读