Not write out all dates on an axis, Matplotlib

前端 未结 1 569
醉梦人生
醉梦人生 2020-12-16 09:04

Take a look at this example:

import datetime as dt
from matplotlib import pyplot as plt 
import matplotlib.dates as mdates
x = []
d = dt.datetime(2013, 7, 4)         


        
相关标签:
1条回答
  • 2020-12-16 09:14

    You can specify an interval argument to the DateLocator as in the following. With e.g. interval=5 the locator places ticks at every 5th date. Also, place the autofmt_xdate() after the bar method to get the desired output.

    import datetime as dt
    from matplotlib import pyplot as plt 
    import matplotlib.dates as mdates
    x = []
    d = dt.datetime(2013, 7, 4)
    for i in range(30):
            d = d+dt.timedelta(days=1)
            x.append(d)
    
    y = range(len(x))
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
    plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
    plt.bar(x, y, align='center') # center the bars on their x-values
    plt.title('DateLocator with interval=5')
    plt.gcf().autofmt_xdate()
    plt.show()
    

    Bar plot with ticks at every 5th date.

    With interval=3 you will get a tick for every 3rd date:

    Bar plot with ticks at every 3rd date.

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