Pandas dataframe groupby plot

前端 未结 2 1173
一个人的身影
一个人的身影 2020-11-27 13:21

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条回答
  • 2020-11-27 13:57

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

    0 讨论(0)
  • 2020-11-27 14:06

    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

    0 讨论(0)
提交回复
热议问题