Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ dữ liệu theo ngày cụ thể trên trục X trong Matplotlib

Để vẽ dữ liệu với trục X là các ngày tháng cụ thể, ta chuyển chuỗi ngày thành đối tượng datetime và dùng mdates.DateFormatter và mdates.DayLocator.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo danh sách chuỗi ngày, chuyển sang datetime.date bằng strptime.
  • Tạo dữ liệu y.
  • Lấy axes hiện tại, đặt formatter và locator cho trục x.
  • Vẽ bằng plot().
  • Hiển thị bằng show().

Ví dụ

from datetime import datetime
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2021", "01/03/2021", "01/04/2021", "01/05/2021", "01/06/2021"]
x = [datetime.strptime(d, "%m/%d/%Y").date() for d in dates]
y = [1, 5, 3, 8, 4]
ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.plot(x, y)
plt.show()

Kết quả

Vẽ dữ liệu theo ngày cụ thể trên trục X trong Matplotlib