在 Matplotlib 中使用日期时间索引绘制 pd df 会由于错误解析日期时间值而导致 ValueError

C H*_*cht 4 python formatting datetime matplotlib pandas

我正在尝试绘制 a pandas.DataFrame,但出现无法解释的 ValueError 。这是导致问题的示例代码:

import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
import matplotlib.dates as mdates

weekday_fmt = mdates.DateFormatter('%a %H:%M')
test_csv = 'datetime,x1,x2,x3,x4,x5,x6\n' \
           '2021-12-06 00:00:00,8,42,14,23,12,2\n' \
           '2021-12-06 00:15:00,17,86,68,86,92,45\n' \
           '2021-12-06 00:30:00,44,49,81,26,2,95\n' \
           '2021-12-06 00:45:00,35,78,33,18,80,67'
test_df = pd.read_csv(StringIO(test_csv), index_col=0)
test_df.index = pd.to_datetime(test_df.index)
plt.figure()
ax = test_df.plot()
ax.set_xlabel(f'Weekly aggregation')
ax.set_ylabel('y-label')
fig = plt.gcf()
fig.set_size_inches(12.15, 5)
ax.get_legend().remove()
ax.xaxis.set_major_formatter(weekday_fmt) # This and the following line are the ones causing the issues
ax.xaxis.set_minor_formatter(weekday_fmt)
plt.show()
Run Code Online (Sandbox Code Playgroud)

如果删除这两个格式行,代码就会运行,但如果我将它们留在那里,则会收到 ValueError:ValueError: Date ordinal 27312480 converts to 76749-01-12T00:00:00.000000 (using epoch 1970-01-01T00:00:00), but Matplotlib dates must be between year 0001 and 9999.

原因似乎是pandas和matplotlib中datetime的转换不兼容。plot这可能可以通过不使用pandas 的内置函数来规避。还有别的办法吗?谢谢!

我的包版本是:

pandas                    1.3.4 
numpy                     1.19.5 
matplotlib                3.4.2 
python                    3.8.10
Run Code Online (Sandbox Code Playgroud)

C H*_*cht 9

感谢 Jody Klymak 和 MrFuppes 的评论,我发现答案很简单ax = test_df.plot(x_compat=True)。对于将来遇到这种情况的任何人,这里是对正在发生的事情的完整解释:

当使用绘图函数时,pandas 接管 x-tick(以及可能的其他功能)的格式。显示给 matplotlib 的所选 x-tick-值不需要与预期相符。在所示示例中,该函数ax.get_xlim()返回(27312480.0, 27312525.0)。使用x_compat=True强制 pandas 将正确的值传递给 matplotlib,然后进行格式化。由于我从收到的错误消息中不清楚这一点,因此这篇文章可能会帮助未来的查看者搜索该错误消息。