python - 如何从 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:第一个参数必须是一个序列
谁能帮我绘制这两个变量的图表?
解决方案
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 # ^^^^^^^
推荐阅读
- node.js - docker build 卡在 pm2 start
- ckeditor - 插入后如何将光标移到跨度元素之外?
- flutter - 如何在颤动中更改文本按钮的背景颜色?
- react-native - 为什么我的 React Native 输入字段会不断重置为其初始值?
- c# - StackExchange.Redis 命令超时问题
- php - 碳格式只有闰年的年和日
- android - ConstraintLayout Slide Transition 动画在动画结束前显示视图的全高
- php - 如何使用 PHP 在 twilio 来电显示手机号码列表中添加手机号码?
- python - 如何从文件夹中动态导入脚本并在 Python 中动态执行函数?
- android - 将前置摄像头更改为后置摄像头时的摄像头 X CameraSelector 问题