Matplotlib with dates - changing labels and ticks for monthly data

前端 未结 1 2009
时光说笑
时光说笑 2021-01-15 04:15

I have a dataframe like this:

data_ = list(range(106))
index_ =  pd.period_range(\'3/1/2004\', \'12/1/2012\', freq=\'M\')
df2_ = pd.DataFrame(data = data_, i         


        
相关标签:
1条回答
  • 2021-01-15 04:56

    With regards to constructing the timedelta, datetime.timdelta() doesn’t have a parameter to specify months, so it’s probably convenient to stick to pd.date_range(). However, I found that objects of type pandas.tslib.Timestamp don’t play nice with matplotlib ticks so you could convert them to datetime.date objects like so

    index_ = [pd.to_datetime(date, format='%Y-%m-%d').date() 
            for date in pd.date_range('2004-03-01', '2012-12-01', freq="M")]
    

    It’s possible to add gridlines and customise axes labels by first defining a matplotlib axes object, and then passing this to DataFrame.plot()

    ax = plt.axes()
    df2_.plot(ax=ax)
    

    Now you can add vertical gridlines to your plot

    ax.xaxis.grid(True)
    

    And specify quarterly xticks labels by using matplotlib.dates.MonthLocator and setting the interval to 3

    ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))
    

    And finally, I found the ticks to be to be very crowded so I formatted them to get a nicer fit

    ax.xaxis.set_major_formatter(dates.DateFormatter('%b %y'))
    labels = ax.get_xticklabels()
    plt.setp(labels, rotation=85, fontsize=8)
    

    To produce the following:

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