如何从 pandas 数据框创建 hexbin 图

How to create a hexbin plot from a pandas dataframe

我有这个数据框:

! 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: First argument must be a sequence

谁能帮我画出这两个变量?

ValueError: First argument must be a sequence

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


因为你已经有一个dataframe,用pandas绘图是最简单的,但是如果你指定源df:

,纯matplotlib仍然是可能的
  • 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
    #                                       ^^^^^^^