Pandas 数据框分组图 [英] Pandas dataframe groupby plot
本文介绍了Pandas 数据框分组图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个结构为:
日期行情 adj_close0 2016-11-21 苹果 111.7301 2016-11-22 苹果 111.8002 2016-11-23 苹果 111.2303 2016-11-25 苹果 111.7904 2016-11-28 苹果 111.570...8 2016-11-21 ACN 119.6809 2016-11-22 ACN 119.48010 2016-11-23 ACN 119.82011 2016-11-25 乙腈 120.740...
如何根据股票代码绘制 adj_close
与 Date
的关系图?
解决方案
简单的情节,
你可以使用:
df.plot(x='Date',y='adj_close')
或者你可以预先将索引设置为Date
,这样就很容易画出你想要的列了:
df.set_index('Date', inplace=True)df['adj_close'].plot()
<小时>
如果你想要一个带有 ticker
的系列的图表
您需要
<小时>如果你想要一个带有单独子图的图表:
grouped = df.groupby('ticker')ncols=2nrows = int(np.ceil(grouped.ngroups/ncols))图,轴 = plt.subplots(nrows=nrows,ncols=ncols,figsize=(12,4),sharey=True)for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):grouped.get_group(key).plot(ax=ax)ax.legend()plt.show()
I have a dataframe which is structured as:
Date ticker adj_close
0 2016-11-21 AAPL 111.730
1 2016-11-22 AAPL 111.800
2 2016-11-23 AAPL 111.230
3 2016-11-25 AAPL 111.790
4 2016-11-28 AAPL 111.570
...
8 2016-11-21 ACN 119.680
9 2016-11-22 ACN 119.480
10 2016-11-23 ACN 119.820
11 2016-11-25 ACN 120.740
...
How can I plot based on the ticker the adj_close
versus Date
?
解决方案
Simple plot,
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
If you want a chart with one series by ticker
on it
You need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
If you want a chart with individual subplots:
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
这篇关于Pandas 数据框分组图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文