使用 pandas 和 matplotlib 绘图

Plotting with pandas and matplotlib

我正在尝试在 Python 中创建散点图。我有一个具有指定类别的数据框 'df',x 和 y 是列号:

groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(x=group.iloc[:,x], y=group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
fig.savefig(path)

出于某种原因,我得到了一个空的散点图 -- 我做错了什么吗?

ax.plot 没有 xy 参数。

签名是Axes.plot(*args, **kwargs),意思是xy只是简单的位置参数。如果您指定 x=y=,它们将被视为关键字参数并被忽略。

所以从代码中删除 x=y=

ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)

完整示例:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"x":np.random.rand(40), 
                   "y":np.random.rand(40),
                   "category": np.random.choice(list("ABCD"), size=40)})
category = "category"
x=1; y=2
groups = df.groupby(category)
fig, ax = plt.subplots()
for name, group in groups:
    ax.plot(group.iloc[:,x], group.iloc[:,y], marker='o', linestyle='',label=name)
fig = ax.get_figure()
#fig.savefig(path)
plt.show()