2

我想将图表显示为小数小时的函数,其中 x 轴从 24 小时跳到 0 小时。但是,绘制的数量应该跨越日期边界平滑地连接。我可以在 x 轴上使用单调增加的不同时间单位,但我想在 x 轴的整数刻度位置显示小时数,我该怎么做?

hours = [19,20.5,21.5,22.5,23.5,0.5,1.5,2.5,3,4]
list1 = [random.randint(1,10) for x in range(10)]
plt.plot(hours, list1)
4

2 回答 2

2

我假设该hours列表是从更完整的日期结构中剔除时间的结果?

如果您转换日期datetime对象(包括日期信息,因此它们确实是单调的),您可以直接list1针对日期进行绘图。然后你可以

import datetime

d = datetime.datetime.now()
delta = datetime.timedelta(hours=1)
dates = [d]
for j in range(20):
    dates.append(dates[-1] + delta)

date_list = dates
list1 = rand(len(dates))
figure()
ax = gca()
ax.plot(date_list,list1)
ax.xaxis.set_major_locator(
    matplotlib.dates.HourLocator()
)
ax.xaxis.set_major_formatter(
    matplotlib.dates.DateFormatter('%H')
)

从这里改编

代码结果

于 2012-12-04T21:29:45.527 回答
2

好吧,这很脏,现在我会尝试使用另一个答案,但是(在ipython --pylab):

In [1]: def monotonic_hours(h):
    hours = h[:]
    for i, _ in enumerate(h[1:], 1):
        while hours[i-1] > hours[i]:
            hours[i] += 24
    return hours
   ...: 

In [2]: %paste
hours = [19,20.5,21.5,22.5,23.5,0.5,1.5,2.5,3,4]
list1 = [random.randint(1,10) for x in range(10)]

## -- End pasted text --

In [3]: plot(monotonic_hours(hours), list1)
Out[3]: [<matplotlib.lines.Line2D at 0x3271810>]

In [4]: xticks(xticks()[0], [int(h%24) for h in xticks()[0]])

在此处输入图像描述

注意:如果默认值xticks位于整数位置,这是准确的,否则您可以执行类似的操作

ticks = sorted(set(int(round(t)) for t in xticks()[0]))
xticks(ticks, [h%24 for h in ticks])

注2:没有ipython你可以调用一切plt

于 2012-12-04T21:31:36.937 回答