matplotlib日期x轴标签不规则? [英] Irregular matplotlib date x-axis labels?

查看:138
本文介绍了matplotlib日期x轴标签不规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 matplotlib 中有这种格式的日期 x 轴标签:

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

'...,10 月 8 日,11 月 8 日,12 月 8 日,1 月 9 日,2 月 9 日,3 月 9 日,...'

'..., 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?

'...,10 月,11 月,12 月,1 月 9 日,2 月,3 月,...'

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

推荐答案

下面是Jouni的答案,这是一个快速而肮脏的示例:

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()

替代文字http://www.imagechicken.com/uploads/1265573633082937000.png

这篇关于matplotlib日期x轴标签不规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆