Matplotlib:如何使用broken_barh的时间戳?

 tantyana428_673 发布于 2023-01-07 15:48

我有一个pandas数据帧,时间戳作为索引和列中的数值.我想使用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

当我执行上面的代码片段时,我得到'参数必须是字符串或数字'错误.

提前致谢.

1 个回答
  • 据我所知,大熊猫根据索引的频率使用周期值绘制时间序列.这是有道理的,因为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()
    

    带有时间戳的断条

    2023-01-07 15:49 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有