绘制从事件开始到结束的时间矩形 (yAxis)

Plot a rectangle of time (yAxis) from start to end of an event

首先,matplotlib 的新手,从未尝试过绘制矩形。 我的 yAxis 将显示时间(24 小时周期),xAxis 显示每个事件。我需要显示事件何时开始 (HH:MM) 以及何时结束 (HH:MM)。我见过一些水平矩形和一些烛台图(不确定这是否适合我)。每个 xAxis 矩形彼此不相关。我可以生成 canvas 并通过从开始时间减去结束时间来生成矩形上的点来创建经过时间,但我无法让对象显示在图表上。想法? 代码如下:

from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import matplotlib.dates as mdates
from matplotlib.dates import HourLocator
from matplotlib.dates import DateFormatter

fig, ax = plt.subplots()


data = ["20180101T09:28:52.442130", "20180101T09:32:04.672891"]

endTime = datetime.strptime(data[1], "%Y%m%dT%H:%M:%S.%f")
beginTime = datetime.strptime(data[0], "%Y%m%dT%H:%M:%S.%f")

timeDiff = endTime - beginTime
elapseTime = timedelta(days=0, seconds=timeDiff.seconds,\
microseconds=timeDiff.microseconds)
print("elapseTime:", elapseTime)
theStartTime = endTime
theEndTime = theStartTime + elapseTime

# convert to matplotlib date representation
eventStart = mdates.date2num(theStartTime)
eventEnd = mdates.date2num(theEndTime)
eventTime = eventEnd - eventStart

# plot it as a Rectangle
nextEvent = Rectangle((1, eventStart), 1, eventTime, color="blue")
print("nextEvent:", nextEvent)

# locator = mdates.AutoDateLocator()
# locator.intervald[“MINUTELY”] = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45,\   
#  50, 55]
# formatter = mdates.AutoDateFormatter[locator]
# formatter.scale[1/(24.*60.)] = “%M:%S”

timeFormat = mdates.DateFormatter("%H:%M")
ax.set_xlim([1, 5])
ax.yaxis_date()
ax.yaxis.set_major_formatter(timeFormat)
ax.set_ylim([datetime.strptime("23:59:59", "%H:%M:%S"),\ 
   datetime.strptime("00:00:00", "%H:%M:%S")])
ax.set_ylabel("Time(HH:MM)")
ax.set_xlabel("Events")
ax.add_patch(nextEvent)

plt.show()

我看不到数据,但它是根据打印的矩形对象显示的,它不适合 canvas。

我想要实现的是下图(烛台演示)

确实,您的日期时间轴完全关闭了。它的范围是从 1900 年 1 月 1 日的午夜到 1900 年 1 月 2 日的一分钟到午夜。然而你的矩形是在 2018 年的某个时候。

所以解决方法很简单,在设置限制时包括完整的日期时间。

ax.set_ylim([datetime.strptime("20180101 23:59:59", "%Y%m%d %H:%M:%S"), 
             datetime.strptime("20180101 00:00:00", "%Y%m%d %H:%M:%S")])

或者将您的数据定义为发生在 1900 年。

是的,这就是问题所在。设置 canvas 限制时我忽略了一些事情。