Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe groupby plot

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?

like image 656
MCM Avatar asked Jan 05 '17 21:01

MCM


People also ask

What does Groupby size () return?

1) Using pandas groupby size() method The most simple method for pandas groupby count is by using the in-built pandas method named size(). It returns a pandas series that possess the total number of row count for each group.

How do you do Groupby in pandas?

The Hello, World! of pandas GroupBy You call . groupby() and pass the name of the column that you want to group on, which is "state" . Then, you use ["last_name"] to specify the columns on which you want to perform the actual aggregation. You can pass a lot more than just a single column name to .

How do I get Groupby columns in pandas?

You can also reset_index() on your groupby result to get back a dataframe with the name column now accessible. If you perform an operation on a single column the return will be a series with multiindex and you can simply apply pd. DataFrame to it and then reset_index. Show activity on this post.


2 Answers

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) 

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

like image 85
Julien Marrec Avatar answered Sep 21 '22 23:09

Julien Marrec


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

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.

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

like image 26
Yaakov Bressler Avatar answered Sep 20 '22 23:09

Yaakov Bressler