Irregular matplotlib date x-axis labels?

2020-07-29 06:20发布

I currently have date x-axis labels in matplotlib in this format:

'..., Oct 08, Nov 08, Dec 08, Jan 09, Feb 09, Mar 09, ...'

Is it possible to only show the year number for January for every year instead?

'..., Oct, Nov, Dec, Jan 09, Feb, Mar, ...'

标签: matplotlib
2条回答
Bombasti
2楼-- · 2020-07-29 06:40
乱世女痞
3楼-- · 2020-07-29 06:43

Following up on Jouni's answer here's a quick and dirty example:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import random, datetime

# generator to just get 20 dates += 30 days
def nextDate():
      date = datetime.date(2008, 12,01)
      while 1:
        date += datetime.timedelta(days=30)
        yield (date)

nd = nextDate()
some_dates = [nd.next() for i in range(0,20)] #get 20 dates
ys = [random.randint(1,100) for i in range(0,20)] # get dummy y data

plt.plot([i for i in range(0,20)],ys) #plot dummy data

def format_date(x, pos=None):
    date = some_dates[int(x)]
    if date.month == 1: 
      return date.strftime('%b %Y')
    else: return date.strftime('%b')

xAxis = plt.axes().xaxis
xAxis.set_major_locator(ticker.FixedLocator([i for i in range(0,20)])) #show all 20 dates on xaxis
xAxis.set_major_formatter(ticker.FuncFormatter(format_date)) # custom format
for tl in xAxis.get_ticklabels():
      tl.set_fontsize(10)
      tl.set_rotation(30)
      # rotate and pretty up

plt.show()

alt text http://www.imagechicken.com/uploads/1265573633082937000.png

查看更多
登录 后发表回答