Pandas: bar plot with multiIndex dataframe

前端 未结 2 1220
陌清茗
陌清茗 2021-01-05 13:32

I have a pandas DataFrame with a TIMESTAMP column (not the index), and the timestamp format is as follows:

2015-03-31 22:56:45.510
相关标签:
2条回答
  • 2021-01-05 13:56

    The following should work, but it is difficult to test without some data.

    Start by resetting your index to get access to the TIMESTAMP column. Then use strftime to format it to your desired text representation (e.g. mm-yy). Finally, reset the index back to AXLES and TIMESTAMP.

    df = resamp.reset_index()
    df['TIMESTAMP'] = [ts.strftime('%m-%y') for ts in df.TIMESTAMP]
    df.set_index(['AXLES', 'TIMESTAMP'], inplace=True)
    >>> df.xs(3, level=0).plot(kind='bar')
    

    0 讨论(0)
  • 2021-01-05 14:04

    You could generate and set the labels explicitly using ax.xaxis.set_major_formatter with a ticker.FixedFormatter. This will allow you to keep your DataFrame's MultiIndex with timestamp values, while displaying the timestamps in the desired %m-%Y format:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import matplotlib.ticker as ticker
    
    dftest = {'TIMESTAMP':['2014-08-31','2014-09-30','2014-10-31'], 'AXLES':[3, 3, 3], 'CLASS':[5,6,7]}
    dfTest = pd.DataFrame(dftest)
    dfTest.TIMESTAMP = pd.to_datetime(pd.Series(dfTest.TIMESTAMP))
    resamp = dfTest.set_index('TIMESTAMP').groupby('AXLES').resample('M', how='count').CLASS
    
    ax = resamp[3].plot(kind='bar')
    ticklabels = [timestamp.strftime('%m-%Y') for axle, timestamp in resamp.index]
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: ticklabels[int(x)]))
    plt.gcf().autofmt_xdate()
    
    plt.show()
    

    yields

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