用pandas和matplotlib绘制 [英] Plotting with pandas and matplotlib
本文介绍了用pandas和matplotlib绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Python中创建散点图.我有一个具有指定类别的数据框'df',x和y是列号:
I'm trying to create a scatter plot in Python. I have a dataframe 'df' with a specified category and x and y are column numbers:
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)
由于某种原因,我得到了一个空的散点图-我做错什么了吗?
For some reason, I am getting an empty scatterplot -- Am I doing something wrong?
推荐答案
ax.plot
没有x
和y
自变量.
签名为Axes.plot(*args, **kwargs)
,这意味着x
和y
只是位置参数.如果指定x=
和y=
,它们将被视为关键字参数并被忽略.
The signature is Axes.plot(*args, **kwargs)
, meaning that x
and y
are simply positional arguments. If you specify x=
and y=
they will be treated as keyword arguments and ignored.
因此从代码中删除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()
这篇关于用pandas和matplotlib绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文