仅针对有数据的时期绘制熊猫日内时间序列

chr*_*ise 5 python matplotlib pandas

我有一系列的日内测量。仅在工作日的白天进行测量。当我绘制数据时,pandas 将 xaxis 扩展到整个时间范围,因此该图显示了数据间隙

dfb.loc[:,("value", "exp_1")].plot()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我可以告诉 pandas/matplotlib 忽略索引并且绘图很好,但我想在 x 轴上显示日期

    dfb.loc[:,("value", "exp_1")].plot(ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我还尝试用我的索引定义 xticks,但这导致第一个图表的 x 轴描述混乱

    dfb.loc[:,("value", "exp_1")].plot(xticks=dfb.index)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

有没有办法在保持日期的同时获得像第二个图这样的图?

编辑:这是数据和情节的一个子集

在此处输入图片说明

ptr*_*trj 4

它看起来有点像一个错误。您还可以考虑在https://github.com/pydata/pandas/上创建问题

当我尝试使用频率设置为天或工作日的 DatetimeIndex 时,x 轴不受影响。但如果频率更精细(例如,小时数、营业时间),那么轴确实会延长 - 正如您的情况一样。

解决方法(不确定是否最好)是将数据帧的索引转换为字符串。要么直接设置:

df.index = df.index.astype('str')
Run Code Online (Sandbox Code Playgroud)

或者也许更好地仅针对打印进行更改:

df.set_index(df.index.astype('str')).plot(rot=30)
Run Code Online (Sandbox Code Playgroud)

该参数rot=30是可选的,但如果没有它,标签就会变得混乱。