如何在带有日期x轴的绘图上绘制 FancyBboxPatch。FancyBboxPatch 应该在特定的时间段内延伸,类似于甘特。
import matplotlib.pyplot as plt
import pandas as pd
data = [('2019-04-15', 'Start'), ('2019-05-01', 'Stop')]
date, labels = zip(*data)
frame = pd.DataFrame({'bla': labels}, index=pd.DatetimeIndex(date))
fig, ax = plt.subplots(figsize=(12.5, 2.5))
for index, row in frame.iterrows():
ax.text(index, 0.5, row['bla'])
ax.set_xlim([frame.index[0], frame.index[-1]])
plt.show()
我试着从Matplotlib网站复制粘贴和调整代码。但是,这导致了与日期轴和补丁宽度有关的错误。
更新
我尝试了下面的代码,但是它返回TypeError: unsupported operand type(s) for -: 'Timestamp' and 'float'
。
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches
data = [('2019-04-15', 'Start'), ('2019-05-01', 'Stop')]
date, labels = zip(*data)
frame = pd.DataFrame({'bla': labels}, index=pd.DatetimeIndex(date))
fig, ax = plt.subplots(figsize=(12.5, 2.5))
for index, row in frame.iterrows():
ax.text(index, 0.5, row['bla'])
ax.set_xlim([frame.index[0], frame.index[-1]])
ax.add_patch(
mpatches.FancyBboxPatch(
(frame.index[0],0.5), # xy
100, # width
0.5, # heigth
boxstyle=mpatches.BoxStyle("Round", pad=0.02)
)
)
plt.show()
1条答案
按热度按时间klsxnrf11#
您可以尝试在此处使用
matplotlib.dates.date2num(d)
将日期时间对象转换为Matplotlib日期,如下所示: