Để vẽ hình chữ nhật đánh dấu khoảng thời gian trên trục datetime, chuyển datetime sang số ngày Matplotlib bằng mdates.date2num() và dùng Rectangle patch.
Các bước
- Thiết lập figure size và autolayout.
- Import datetime, timedelta, Rectangle, mdates.
- Tạo figure, axes.
- Xác định startTime, endTime, chuyển sang số: start = mdates.date2num(startTime).
- Tính width = end - start.
- Tạo Rectangle((start, 0), width, 1) và ax.add_patch(rect).
- Đặt locator/formatter cho trục x datetime.
- Giới hạn xlim, ylim và hiển thị.
Ví dụ
from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
startTime = datetime.now()
endTime = startTime + timedelta(seconds=1)
start = mdates.date2num(startTime)
end = mdates.date2num(endTime)
width = end - start
rect = Rectangle((start, 0), width, 1, color='red')
ax.add_patch(rect)
locator = mdates.AutoDateLocator(minticks=3)
formatter = mdates.AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
plt.xlim([start - width, end + width])
plt.ylim([-.5, 1.5])
plt.show()
Kết quả
