Để hiển thị ngày giờ trên trục X trong Matplotlib, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Tạo danh sách dates và giá trị y.
- Lấy trục hiện tại.
- Đặt major date formatter và locator.
- Vẽ x và y bằng phương thức plot().
- Để hiển thị figure, dùng phương thức show().
Ví dụ
from datetime import datetime as dt
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/2020", "01/03/2020", "01/04/2020"]
x_values = [dt.strptime(d, "%m/%d/%Y").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()
formatter = mdates.DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)
plt.show()
Kết quả
