matplotlib HourLocator 窃取我的 x 标签 [英] matplotlib HourLocator steals my x labels
本文介绍了matplotlib HourLocator 窃取我的 x 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我绘制半小时的时间序列时,我的轴标签是奇怪的(例如大约16:33:12h ...)当我使用HourLocator修复此问题(16:33h-> 16:00h)时,我的x标签完全消失了.
When I plot my half hourly time series, my axis labels are odd (like 16:33:12h or so...) When I use HourLocator to fix this (16:33h -> 16:00h), then my x label disappear completely.
我的代码是:
from datetime import date, timedelta, datetime, time
from matplotlib.dates import DayLocator, HourLocator
import matplotlib.pyplot as plt
start = time(0, 0, 0)
delta = timedelta(minutes=30)
times = []
for i in range(len(day_load)):
dt = datetime.combine(date.today(), time(0, 0)) + delta * i
times.append(dt.time())
load = [i/48 for i in range(48)]
fig, ax = plt.subplots()
ax.plot_date(times, load)
ax.xaxis.set_major_locator(HourLocator())
plt.show()
如何获得偶数"标签(以最佳实践方式-我不想为其他所有图再次重写代码).当我评论倒数第二行时,我得到正常的奇数"标签:(
How can I achieve "even" labels (in a best practice way - I don't want to rewrite code for every other plot again). When I comment second last line, I get normal "odd" labels :(
感谢您的回答!
推荐答案
有两个主要问题:
- 您需要处理完整的日期时间对象,而不仅仅是时间.因此,您应该直接添加
dt
而不是dt.time()
. - 您不仅需要一个定位器,而且还需要一个格式化程序来生成漂亮的刻度标签.在这里,您可以使用
DateFormatter("%H:%M")
来显示小时和分钟.
- You need to work with complete datetime objects, not only with time. So instead of
dt.time()
you should appenddt
directly. - You not only need a locator, but also a formatter to produce nice ticklabels. Here you may use a
DateFormatter("%H:%M")
to show hours and minutes.
完整代码:
from datetime import date, timedelta, datetime, time
from matplotlib.dates import DayLocator, HourLocator,DateFormatter
import matplotlib.pyplot as plt
start = time(0, 0, 0)
delta = timedelta(minutes=30)
times = []
n=48
for i in range(n):
# use complete datetime object, not only time
dt = datetime.combine(date.today(), time(0, 0)) + delta * i
times.append(dt)
load = [i/float(n) for i in range(n)]
fig, ax = plt.subplots()
ax.plot_date(times, load)
# set a locator, as well as a formatter
ax.xaxis.set_major_locator(HourLocator())
ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))
#optionally rotate the labels and make more space for them
fig.autofmt_xdate()
plt.show()
这篇关于matplotlib HourLocator 窃取我的 x 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文