【问题标题】:Matplotlib: How to use timestamps with broken_barh?Matplotlib:如何在 broken_barh 中使用时间戳?
【发布时间】:2014-06-26 08:34:47
【问题描述】:

我有一个熊猫数据框,其中时间戳作为索引和列中的数值。 我想使用 broken_bar 绘制矩形以突出显示时间序列的某些部分。 如何在 broken_barh 中使用时间戳?

df.plot(ax = ax)
ax.broken_barh([(startTs, pd.offsets.Week())], (10,50), facecolors = colors, alpha = 0.25)
# Where type(startTs) is pandas.tslib.Timestamp

当我执行上面的 sn-p 时,我得到 'argument must be a string or a number' 错误。

提前致谢。

【问题讨论】:

    标签: python matplotlib plot pandas


    【解决方案1】:

    据我了解,pandas 根据索引的频率使用周期值来绘制时间序列。这是有道理的,因为 matplotlib 仅将数字理解为轴的值,因此您对 broken_barh 的调用失败,因为您传递的是非数字值。

    要获取一个时间戳的整数值,您需要使用.to_period()。见:

    In [110]: pd.to_datetime('2014-04-02').to_period('D').ordinal
    Out[110]: 16162
    
    In [111]: pd.to_datetime('2014-04-02').to_period('W').ordinal
    Out[111]: 2310
    

    然后,根据您的时间戳间隔(天、周、月等),您需要确定要用于折断条的宽度。

    在下面的示例中,频率为 1 天,一周的条形宽度为 7 个单位。

    import numpy as np
    import matplotlib.pylab as plt
    import pandas as pd
    
    idx = pd.date_range('2013-04-01', '2013-05-18', freq='D')
    df = pd.DataFrame({'values': np.random.randn(len(idx))}, index=idx)
    ax = df.plot()
    
    start_period = idx[0].to_period('D').ordinal
    bar1 = [(start_period, 7), (start_period + 10, 5), (start_period + 25, 4)]
    bar2 = [(start_period, 1), (start_period + 22, 3), (start_period + 40, 2)]
    ax.broken_barh(bar1, [2, .2], facecolor='red')
    ax.broken_barh(bar2, [-2, .2], facecolor='green')
    plt.show()
    

    【讨论】:

    • 嗨罗兰多。感谢您的回答-直到最后一次熊猫更新为止,它一直对我有用。现在broken_barh 导致TypeError: not all arguments converted during string formatting。你也许知道如何解决它?
    • 同时作为一种解决方法:删除序数并使用 matplotlib.dates.date2num 此处建议的 stackoverflow.com/a/11056898/3160867 似乎正在解决问题
    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 2023-04-05
    • 2014-11-20
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多