使用 pandas 和 matplotlib 绘图

2024-03-15

我正在尝试用 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 https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html不具有x and y论据。

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

所以删除x= and 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pandas 和 matplotlib 绘图 的相关文章

随机推荐