我正在嘗試繪制一個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), but Matplotlib dates must be between year 0001 and 9999.
原因似乎是 pandas 和 matplotlib 中日期時間的轉換不兼容。plot這可以通過不使用pandas的內置函式來規避。還有其他方法嗎?謝謝!
我的包版本是:
pandas 1.3.4
numpy 1.19.5
matplotlib 3.4.2
python 3.8.10
uj5u.com熱心網友回復:
感謝 Jody Klymak 和 MrFuppes 的評論,我發現答案很簡單ax = test_df.plot(x_compat=True)。對于將來偶然發現此問題的任何人,以下是對正在發生的事情的完整解釋:
使用繪圖功能時,pandas 會接管 x-tick 的格式(可能還有其他功能)。顯示給 matplotlib 的選定 x-tick-values 不需要與預期的一致。在所示示例中,函式ax.get_xlim()回傳(27312480.0, 27312525.0). 使用x_compat=True強制 pandas 將正確的值交給 matplotlib,然后進行格式化。由于我從收到的錯誤訊息中不清楚這一點,因此這篇文章可能會幫助未來的觀眾搜索該錯誤訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410915.html
標籤:
