【问题标题】:Matplotlib timedelta64 index as x-axisMatplotlib timedelta64 索引作为 x 轴
【发布时间】:2018-11-15 23:17:11
【问题描述】:

我想绘制一个数据帧,它有一个 timedelta64 索引,索引在 x 轴上。

索引如下所示:

In [75]: test.index
Out[75]: 
TimedeltaIndex([       '00:00:00', '00:00:00.020000', '00:00:00.040000',
                '00:00:00.060000', '00:00:00.080000', '00:00:00.100000',
                '00:00:00.120000', '00:00:00.140000', '00:00:00.160000',
                '00:00:00.180000',
                ...
                '07:29:31.660000', '07:29:31.680000', '07:29:31.700000',
                '07:29:31.720000', '07:29:31.740000', '07:29:31.760000',
                '07:29:31.780000', '07:29:31.800000', '07:29:31.820000',
                '07:29:31.840000'],
               dtype='timedelta64[ns]', name='master', length=923486, freq=None)

当我简单地绘制这个数据框时:

plt.plot(test)

我希望得到 x 轴上的 timedeltaindex。但是,我只是在 x 轴上得到这个:

我怎样才能在 x 轴上获得我的 TimedeltaIndex?

【问题讨论】:

    标签: python matplotlib spyder timedelta


    【解决方案1】:

    首先,您可以直接使用 pandas 来绘制数据。 IE。而不是 plt.plot(df) 你可以使用

    df.plot()
    

    这将在轴上显示正确的时间增量。

    如果出于任何原因您需要使用 matplotlib 进行绘图,例如因为您有不等间隔的时间戳,您需要将TimedeltaIndex 转换为绝对日期时间。选择一些(任意)开始,您可以将增量添加到开始以获得一些绝对日期时间。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    index = pd.to_timedelta(np.arange(50,100), unit='s')
    
    df = pd.DataFrame(np.arange(50), index=index)
    
    start=pd.Timestamp('20180606')
    plt.plot(start+df.index, df)
    
    plt.show()
    

    【讨论】:

    • 非常感谢!这正是我一直在寻找的。如果其他人正在寻找同样的东西,这就是我如何让它看起来像我需要的那样:start = pd.Timestamp('20180606') new_index = start + test.index test.index = new_index index_plot = new_index[::20000] # to reduce the number of labels on x-axis labels = index_plot.strftime('%H:%M:%S') plt.plot(test) plt.xticks(index_plot, labels, rotation=60) plt.show() 这也是一种解决方法,但我非常适合我。
    • df.plot() 也不起作用。它显示轴的标签,但不显示任何刻度标签
    • @endolith 很有趣,但没有帮助。在哪个版本的 matplotlib 和 pandas 中哪些代码不起作用? (最好使用一个新问题。)
    • @endolith 在此答案的代码中将plt.plot(...) 替换为df.plot() 并使用matplotlib 0.25.2 和matplotlib 3.1.1 运行它会得到this figure。如果您看到不同的东西,或者有其他问题,我再次建议使用minimal reproducible example 创建一个新问题。
    • @endolith 这是因为 pandas 不会将不等间距的值视为时间序列。因此,它回退到使用 matplotlib;但 matplotlib 不理解 timedeltas。所以在那种情况下你真的需要使用 matplotlib。
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2017-10-19
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2011-11-25
    相关资源
    最近更新 更多