Plotting a Datetime Bar Graph with Pandas with different xlabels

前端 未结 1 1163
不知归路
不知归路 2021-01-24 03:31

I would like to plot a bar graph that has only a few entries of data in each column of a pandas DataFrame with a bar graph. This is successful, but not only does it have the wro

相关标签:
1条回答
  • 2021-01-24 04:08

    Look at this code:

    import pandas as pd
    import numpy as np
    from datetime import datetime 
    import matplotlib.pylab as plt
    from matplotlib.dates import DateFormatter
    
    # Sample data
    df_origin = pd.DataFrame(pd.date_range(datetime(2014,6,28,12,0,0), 
     datetime(2014,8,30,12,0,0), freq='1H'), columns=['Valid Time'])
    df_origin = df_origin .set_index('Valid Time')
    df_origin ['Precipitation'] = np.random.uniform(low=0., high=10., size=(len(df_origin.index)))
    df_origin .loc[20:100, 'Precipitation'] = 0.
    df_origin .loc[168:168*2, 'Precipitation'] = 0. # second week has to be dry
    
    # Plotting
    df_origin.plot(y='Precipitation',kind='bar',edgecolor='none',figsize=(16,8),linewidth=2, color=((1,0.502,0)))
    plt.legend(prop={'size':16})
    plt.subplots_adjust(left=.1, right=0.9, top=0.9, bottom=.1)
    plt.title('Precipitation (WRF Model)',fontsize=24)
    plt.ylabel('Hourly Accumulated Precipitation [mm]',fontsize=18,color='black')
    ax = plt.gca()
    plt.gcf().autofmt_xdate()
    
    # skip ticks for X axis
    ax.set_xticklabels([dt.strftime('%Y-%m-%d') for dt in df_origin.index])
    for i, tick in enumerate(ax.xaxis.get_major_ticks()):
        if (i % (24*7) != 0): # 24 hours * 7 days = 1 week
            tick.set_visible(False)
    
    plt.xlabel('Time',fontsize=18,color='black')
    
    plt.show()
    

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