Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

python 3.x - Months as axis ticks

I would like to add monthly ticks to this plot - and it is currently showing ticks of 2015 and 2016 where i would like it to show Jan, Feb...Dec, Jan.

The index of the data that I have begins on 2015-01-01 and ends on 2015-12-31. The code I have so far is:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate

plt.figure(figsize=(20,12))
#ax = plt.add_subplot(111)
plt.plot_date(list(max_group_by15.index), max_group_by15['Data_Value'])
plt.plot_date(list(min_group_by15.index), min_group_by15['Data_Value'])
plt.plot_date(list(min_group_by14.index), min_group_by14['Data_Value'], '-b')
plt.plot_date(list(max_group_by14.index), max_group_by14['Data_Value'], '-r')

plt.legend(['2015 Temp Exceed Prev High', '2015 Temp Below Prev Low', 'Min Temp 2005-2014', 'Max Temp 2005-2014'])
plt.gca().fill_between(min_group_by14.index, min_group_by14['Data_Value'], max_group_by14['Data_Value'], facecolor = 'blue', alpha =.25)



plt.xlabel('Month')
plt.ylabel('Degrees (Celsius)')
plt.title('Daily High and low temp in Ann Arbor area from 2005-2014')

locator = mdate.MonthLocator()
plt.gca().xaxis.set_major_locator(locator)

Produces this plot:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tough to try without your exact data, but I think you're simply missing a call to set_major_formatter.

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Generate some random date-time data
numdays = 500
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
y = np.random.rand(numdays)

# Set the locator
locator = mdates.MonthLocator()  # every month
# Specify the format - %b gives us Jan, Feb...
fmt = mdates.DateFormatter('%b')


plt.plot(date_list,y)
X = plt.gca().xaxis
X.set_major_locator(locator)
# Specify formatter
X.set_major_formatter(fmt)
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...