从偶数的开始到结束绘制一个时间矩形(Y轴)

2024-09-30 10:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

enter image description here

我无法看到数据,但它似乎基于矩形对象的打印它不适合画布。你知道吗

我想实现的是下面的图像(烛台演示) enter image description here


Tags: fromimportdatetimematplotlibashh时间ax
2条回答

事实上,你的日期时间轴完全偏离了。从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年。你知道吗

是的,这就是问题所在。我在设置画布限制时忽略了一些东西。你知道吗

相关问题 更多 >

    热门问题