首頁  >  文章  >  後端開發  >  如何在 Pandas 線圖的 x 軸上正確顯示日期?

如何在 Pandas 線圖的 x 軸上正確顯示日期?

Patricia Arquette
Patricia Arquette原創
2024-10-26 18:49:02693瀏覽

How to Correctly Display Dates on the x-axis of a Pandas Line Plot?

在Pandas 資料框圖的x 軸上顯示日期

簡介

要在Pandas 線圖的x 軸上顯示日期,set_index () 方法可用來將包含日期值的資料列轉換為DataFrame 的索引。但是,當使用 matplotlib 的 DateFormatter 函數格式化日期時,可能會出現某些問題。

DateFormatter 問題

下圖說明了在程式碼中加入DateFormatter 時出現的問題:

[日期格式不正確的線圖圖片]

請注意,日期從5-24 開始,而不是5-25,並且星期四被錯誤地標記為2017 年的5-25。這通常是由於時區 - pandas 和 matplotlib 日期時間實用程式之間的相關問題或不相容性。

Pandas 和 Matplotlib 日期時間物件不相容

Pandas 和 matplotlib 日期時間物件通常不相容。當嘗試在使用 pandas 建立的日期軸上使用 matplotlib 日期物件時,可能會出現問題。

造成這種情況的一個原因是 pandas 日期時間對像被轉換為浮點數,表示自 0001-01 以來的天數-01 UTC,加 1。此格式與 matplotlib 的日期時間格式不同。

使用 x_compat

要解決日期格式問題,可以使用 x_compat=True 參數傳遞給plot()方法。這指示 pandas 不要使用自己的日期時間格式,從而允許使用 matplotlib 的股票代碼、定位器和格式化程式。

使用 Matplotlib 繪製日期時間

或者,如果需要更精確的日期時間格式,matplotlib可用於繪圖和格式化。以下程式碼片段示範了這種方法:

<code class="python">import matplotlib.pyplot as plt
import matplotlib.dates as dates

# Create the DataFrame
df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
df['date'] = pd.to_datetime(df['date'])

# Create the line plot
plt.plot(df['date'], df['ratio1'])

# Set major locator and formatter for the x-axis
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))

# Invert the x-axis for chronological order
plt.gca().invert_xaxis()

# Autofmt the x-axis for optimal placement of dates
plt.gcf().autofmt_xdate(rotation=0, ha="center")

# Display the plot
plt.show()</code>

此修訂後的程式碼將產生一個線圖,其中 x 軸上的日期格式準確。

以上是如何在 Pandas 線圖的 x 軸上正確顯示日期?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn