Python Pandas 数据框分组图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41494942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:05:10  来源:igfitidea点击:

Pandas dataframe groupby plot

pythonpandasmatplotlibdataframe

提问by MCM

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_closeversus Date?

我怎样才能情节基础上,股票的adj_close对比Date

回答by Julien Marrec

Simple plot,

简单的剧情,

you can use:

您可以使用:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Datebeforehand, then it's easy to plot the column you want:

或者你可以Date预先设置索引,然后很容易绘制你想要的列:

df.set_index('Date', inplace=True)
df['adj_close'].plot()


If you want a chart with one series by tickeron it

如果你想用一个系列的图表由ticker

You need to groupbybefore:

您需要先分组

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here

在此处输入图片说明



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()

enter image description here

在此处输入图片说明

回答by Yaakov Bressler

Similar to Julien's answer above, I had success with the following:

与上述 Julien 的回答类似,我在以下方面取得了成功:

fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
    ax.plot(grp['Date'], grp['adj_close'], label=key)

ax.legend()
plt.show()

This solution might be more relevant if you want more control in matlab.

如果您想在 matlab 中进行更多控制,则此解决方案可能更相关。

Solution inspired by: https://stackoverflow.com/a/52526454/10521959

解决方案灵感来自:https: //stackoverflow.com/a/52526454/10521959