Change frequency of x-axis tick label of datetime data in python bar chart using matplotlib

后端 未结 1 2002
南旧
南旧 2020-12-04 00:35

I have a script that takes multiple .csv files and outputs multiple bar plots. The data are daily rainfall totals and so the x-axis is the date in daytime format %d %m

相关标签:
1条回答
  • 2020-12-04 01:16

    It is not easy, but this works:

    #sample df with dates of one year, rf are random integers
    np.random.seed(100)
    N = 365
    start = pd.to_datetime('2015-02-24')
    rng = pd.date_range(start, periods=N)
    
    final = pd.DataFrame({'date': rng, 'rf': np.random.randint(50, size=N)})  
    print (final.head())
            date  rf
    0 2015-02-24   8
    1 2015-02-25  24
    2 2015-02-26   3
    3 2015-02-27  39
    4 2015-02-28  23
    
    fn = 'suptitle'
    #rot - ratation of labels in axis x 
    ax = final.plot(x='date', y='rf', kind='bar', rot='45')
    plt.suptitle('{} Rainfall 2015-2016'.format(fn), fontsize=20)
    plt.xlabel('Date', fontsize=18)
    plt.ylabel('Rain / mm', fontsize=16)
    #set cusom format of dates
    ticklabels = final.date.dt.strftime('%Y-%m-%d')
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
    
    #show only each 30th label, another are not visible
    spacing = 30
    visible = ax.xaxis.get_ticklabels()[::spacing]
    for label in ax.xaxis.get_ticklabels():
        if label not in visible:
            label.set_visible(False)
    
    plt.show()
    

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