如何在帶有日期 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()
uj5u.com熱心網友回復:
您可以嘗試使用matplotlib.dates.date2num(d)from here將日期時間物件轉換為 Matplotlib 日期,如下所示:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches
import matplotlib.dates as dates
data = [('2019-04-15', 'Start'), ('2019-05-01', 'Stop')]
date, labels = zip(*data)
frame = pd.DataFrame({'bla': labels}, index=pd.DatetimeIndex(date))
print(f'frame.index[0] {frame.index[0]}')
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(
(dates.date2num(frame.index[0]),0.5), # Conversion
100, # width
0.5, # heigth
boxstyle=mpatches.BoxStyle("Round", pad=0.02)
)
)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533882.html
上一篇:按屬性查找所有xml元素并使用t-sql更改它們的值
下一篇:python編譯時間很長
