[英]How do I fix the datetime x-axis on my Python Plot?
我正在嘗試 plot 時間 x 降水圖,但是,x 軸上的值與 y 軸上的值不匹配。 plot 本身是正確的,但 x 軸不是。 上下文是我創建了一個 Prophet model 來預測月降水量,在生成值之后,我根據預測繪制了測試圖,雖然線條看起來是正確的,但日期看起來向左移動了一個“單位”:
降水量 x 月:
測試值:
Date Precipitation
443 2020-12-31 273.2
444 2021-01-31 215.5
445 2021-02-28 180.6
446 2021-03-31 138.4
447 2021-04-30 54.4
448 2021-05-31 44.4
449 2021-06-30 16.2
450 2021-07-31 39.4
451 2021-08-31 44.4
452 2021-09-30 39.5
453 2021-10-31 91.9
454 2021-11-30 98.6
455 2021-12-31 127.3
456 2022-01-31 308.5
預測值:
Date Precipitation
443 2020-12-31 133.7
444 2021-01-31 272.0
445 2021-02-28 222.0
446 2021-03-31 177.3
447 2021-04-30 75.9
448 2021-05-31 81.5
449 2021-06-30 31.9
450 2021-07-31 41.7
451 2021-08-31 28.9
452 2021-09-30 42.9
453 2021-10-31 111.4
454 2021-11-30 129.5
455 2021-12-31 126.2
456 2022-01-31 299.1
我們可以觀察到第一個值應該是 2020-12,但事實並非如此。
fig = plt.figure(figsize=(12, 8))
plt.plot(test.Date, test.Precipitation, 's-r')
plt.plot(previsao.Date, previsao.Precipitation, 's-b')
plt.title('Precipitação por Mês na Cidade de São Paulo em $mm$', fontsize=20)
plt.ylabel('Precipitação ($mm$)', fontsize=12)
plt.xlabel('Ano')
plt.legend(['Real', 'Previsão']);
plt.show()
誰能指出我在這里做錯了什么? 我相信我在繪制圖表時做錯了什么,但我無法弄清楚。
您需要做幾件事。 首先確保日期列是日期時間格式。 您可以使用test.info()
和previsao.info()
進行檢查,並查看數據類型是否為日期時間。 如果沒有,請使用pd.to_datetime()
。 顯示日期的默認格式是該月的第一天。 因此,您看到的日期看起來像是偏移了一個月。 但是,由於您的日期是該月的最后一天,因此您需要使用 MonthLocator 中的MonthLocator
bymonthday=-1
更改顯示以顯示最后日期。 最后,我使用“YYYY-MM-DD”格式進行顯示,以便您可以看到完整的日期並旋轉刻度標簽。 您可以對其進行編輯以滿足您的需要。 更新后的代碼如下所示。 希望這就是您要找的。
fig = plt.figure(figsize=(12, 8))
## Use these if your dates are NOT already in datetime format
test['Date']=pd.to_datetime(test['Date'])
previsao['Date']=pd.to_datetime(previsao['Date'])
plt.plot(test.Date, test.Precipitation, 's-r')
plt.plot(previsao.Date, previsao.Precipitation, 's-b')
plt.title('Precipitação por Mês na Cidade de São Paulo em $mm$', fontsize=20)
plt.ylabel('Precipitação ($mm$)', fontsize=12)
plt.xlabel('Ano')
plt.legend(['Real', 'Previsão']);
## Added code here
import matplotlib.dates as mdates ## Import required library
months = mdates.MonthLocator(interval=1, bymonthday=-1) ## 1 month apart & show last date
plt.gca().xaxis.set_major_locator(months) ## Set months as major locator
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ##Display format - update here to change
plt.xticks(rotation=45, ha='right') ##Adjust angle and horizontal align right
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.