Matplotlib - 日期刻度



在一般的繪圖中,日期刻度指的是帶有日期或時間資訊的繪圖的軸上的刻度線或標記的標籤,替換預設的數值。此功能在處理時間序列資料時特別有用。

下圖說明了繪圖上的日期刻度 -

dateticks_Intro

Matplotlib 中的日期刻度

Matplotlib 提供了強大的工具來繪製時間序列資料,允許使用者在刻度線或標記上表示日期或時間,而不是預設的數值(日期刻度)。該庫透過將日期例項轉換為自預設紀元(1970-01-01T00:00:00)以來的天數來簡化處理日期的過程。這種轉換以及刻度定位和格式化都在後臺進行,對使用者來說是透明的。

matplotlib.dates 模組在處理各種日期相關功能方面發揮著關鍵作用。這包括將資料轉換為日期時間物件、格式化日期刻度標籤以及設定刻度的頻率。

使用預設格式化器的基本日期刻度

Matplotlib 使用 AutoDateLocatorAutoDateFormatter 類分別設定軸的預設刻度定位器和格式化器。

示例

此示例演示了時間序列資料的繪圖,此處 Matplotlib 自動處理日期格式。

import numpy as np
import matplotlib.pylab as plt

# Generate an array of dates
times = np.arange(np.datetime64('2023-01-02'),
   np.datetime64('2024-02-03'), np.timedelta64(75, 'm'))
# Generate random data for y axis
y = np.random.randn(len(times))

# Create subplots
fig, ax = plt.subplots(figsize=(7,4), facecolor='.9')
ax.plot(times, y)
ax.set_xlabel('Dataticks',color='xkcd:crimson')
ax.set_ylabel('Random data',color='xkcd:black')
plt.show()

輸出

執行上述程式碼後,我們將獲得以下輸出 -

dateticks_Ex1

使用 DateFormatter 自定義日期刻度

對於日期格式的手動自定義,Matplotlib 提供了 DateFormatter 模組,允許使用者更改日期刻度的格式。

示例

此示例演示瞭如何手動自定義日期刻度的格式。

import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

# Generate an array of dates    
times = np.arange(np.datetime64('2023-01-02'),
   np.datetime64('2024-02-03'), np.timedelta64(75, 'm'))

# Generate random data for y axis
y = np.random.randn(len(times))

# Create subplots
fig, ax = plt.subplots(figsize=(7,5))
ax.plot(times, y)
ax.set_title('Customizing Dateticks using DateFormatter')

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
# Rotates and right-aligns the x labels so they don't overlap each other.
for label in ax.get_xticklabels(which='major'):
   label.set(rotation=30, horizontalalignment='right')

plt.show()

輸出

執行上述程式碼後,我們將獲得以下輸出 -

dateticks_Ex2

使用 ConciseDateFormatter 進行高階格式化

Matplotlib 中的 ConciseDateFormatter 類簡化並增強了日期刻度的外觀。此格式化器旨在最佳化刻度標籤字串的選擇並最大程度地減少其長度,這通常消除了旋轉標籤的需要。

示例

此示例使用 ConciseDateFormatter 和 AutoDateLocator 類來設定繪圖的最佳刻度限制和日期格式。

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

# Define a starting date
base_date = datetime.datetime(2023, 12, 31)

# Generate an array of dates with a time delta of 2 hours
num_hours = 732
dates = np.array([base_date + datetime.timedelta(hours=(2 * i)) for i in range(num_hours)])
date_length = len(dates)

# Generate random data for the y-axis
np.random.seed(1967801)
y_axis = np.cumsum(np.random.randn(date_length))

# Define different date ranges
date_ranges = [
   (np.datetime64('2024-01'), np.datetime64('2024-03')),
   (np.datetime64('2023-12-31'), np.datetime64('2024-01-31')),
   (np.datetime64('2023-12-31 23:59'), np.datetime64('2024-01-01 13:20'))
]

# Create subplots for each date range
figure, axes = plt.subplots(3, 1, constrained_layout=True, figsize=(6, 6))

for nn, ax in enumerate(axes):
   # AutoDateLocator and ConciseDateFormatter for date formatting
   locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
   formatter = mdates.ConciseDateFormatter(locator)

   ax.xaxis.set_major_locator(locator)
   ax.xaxis.set_major_formatter(formatter)

   # Plot the random data within the specified date range
   ax.plot(dates, y_axis)
   ax.set_xlim(date_ranges[nn])

axes[0].set_title('Concise Date Formatter')

# Show the plot
plt.show()

輸出

執行上述程式碼後,我們將獲得以下輸出 -

dateticks_Ex3
廣告