matplotlib |TypeError:不支援的算子类型-:“时间戳”和“浮点数”

hmae6n7t  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(124)

如何在带有日期x轴的绘图上绘制 FancyBboxPatchFancyBboxPatch 应该在特定的时间段内延伸,类似于甘特。

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

klsxnrf11#

您可以尝试在此处使用matplotlib.dates.date2num(d)将日期时间对象转换为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()

相关问题