gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:54:26 25 4
gpt4 key购买 nike

我正在尝试绘制一个 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()

如果两个格式化行被删除,代码会运行,但如果我把它们留在那儿,我会得到一个 ValueError: ValueError: Date ordinal 27312480 converts to 76749-01-12T00:00:00.000000 (using epoch 1970-01-01T00:00:00),但 Matplotlib 日期必须介于 0001 年和 9999 之间。

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

我的包版本是:

pandas                    1.3.4 
numpy 1.19.5
matplotlib 3.4.2
python 3.8.10

最佳答案

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

当使用 plot-function 时,pandas 会接管 x-tick 的格式(可能还有其他功能)。显示给 matplotlib 的选定 x-tick-values 不需要与人们期望的相符。在所示示例中,函数 ax.get_xlim() 返回 (27312480.0, 27312525.0)。使用 x_compat=True 强制 pandas 将正确的值交给 matplotlib,然后在其中进行格式化。由于我从收到的错误消息中不清楚这一点,这篇文章可能会帮助 future 的观众搜索该错误消息。

关于python - 由于日期时间值的错误解析,在 Matplotlib 中使用日期时间索引绘制 pd df 会导致 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70620319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com