Tôi cố gắng để vẽ một hình chữ nhật trên một đồ thị với một datetime trục x bằng cách sử dụng đoạn mã sau:Làm thế nào để vẽ một hình chữ nhật trên trục datetime bằng cách sử dụng matplotlib?
from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111)
# Create rectangle
startTime = datetime.now()
width = timedelta(seconds = 1)
endTime = startTime + width
rect = Rectangle((startTime, 0), width, 1, color='yellow')
# Plot rectangle
ax.add_patch(rect) ### ERROR HERE!!! ###
plt.xlim([startTime, endTime])
plt.ylim([0, 1])
plt.show()
Tuy nhiên, tôi nhận được lỗi:
TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'
gì đang xảy ra vậy? (Tôi đang sử dụng phiên bản matplotlib 1.0.1)
Lưu ý rằng nếu các ngày trong trục x là từ 'pandas', bạn cần phải chuyển đổi thành ngày giờ trăn đầu tiên. Dòng 'start = mdates.date2num (startTime)' sẽ là 'start = mdates.date2num (startTime.to_pydatetime())'. Điều tương tự cũng xảy ra với 'kết thúc'. – Luis