我想用下面的样本绘制图表,X轴:'时间',Y轴:'Celcius'。附上代码,我在x轴上[09:00:00.000000 09:05:00.000000 ... 09:30:00.000000]而不是[2013-01-02 09:00 2013-01-02 09] :05 ... 2013-01-02 09:30]。我可以知道将x轴格式化为指定格式的正确方法是什么?
data = {'Celcius': [36.906441135554658, 51.286294403017202], 'Time': [datetime.datetime(2013, 1, 2, 9, 0), datetime.datetime(2013, 1, 2, 9, 30)]}
def plotTemperature(self, data):
logging.debug(data)
t = data.get('Time')
T = data.get('Celcius')
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
days = mdates.DayLocator() # every day
hours = mdates.HourLocator() # every hour
minutes = mdates.MinuteLocator() # every minute
yearsFmt = mdates.DateFormatter('%Y')
hoursFmt = mdates.DateFormatter('%H')
fig, ax = plt.subplots()
ax.plot(t, T)
# format the ticks
# ax.xaxis.set_major_locator(hours)
# ax.xaxis.set_major_formatter(hoursFmt)
# ax.xaxis.set_minor_locator(minutes)
datemin = datetime.datetime(min(t).year, min(t).month, min(t).day, min(t).hour, min(t).minute)
datemax = datetime.datetime(max(t).year, max(t).month, max(t).day, max(t).hour, max(t).minute)
ax.set_xlim(datemin, datemax)
# format the coords message box
def temperature(x): return '$%1.2f'%x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d %H:%M')
ax.format_ydata = temperature
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
好吧,找到了解决方案......
ymdhFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
rule = rrulewrapper(MINUTELY, interval=30)
loc = RRuleLocator(rule)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(ymdhFmt)