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