Giới thiệu
Để vẽ đường đa màu (multicolor line) khi trục X là DatetimeIndex của Pandas, bạn có thể thực hiện theo các bước sau:
- Thiết lập kích thước hình vẽ và điều chỉnh padding.
- Tạo các điểm dữ liệu
d,yvàsbằng numpy. - Tạo một figure và tập hợp subplot.
- Lấy
xval,pvàsdata points bằng numpy. - Tạo instance
LineCollectionvới colormap "hot" và dữ liệus. - Thiết lập major/minor locator và formatter cho trục.
- Tự động điều chỉnh giới hạn hiển thị (autoscale).
- Hiển thị hình vẽ bằng show().
Ví dụ minh họa
import pandas as pd
from matplotlib import pyplot as plt, dates as mdates, collections as c
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = pd.date_range("2021-01-01", "2021-06-01", freq="7D")
y = np.cumsum(np.random.normal(size=len(d)))
s = pd.Series(y, index=d)
fig, ax = plt.subplots()
xval = mdates.date2num(s.index.to_pydatetime())
p = np.array([xval, s.values]).T.reshape(-1, 1, 2)
s = np.concatenate([p[:-1], p[1:]], axis=1)
lc = c.LineCollection(s, cmap="hot")
lc.set_array(xval)
ax.add_collection(lc)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
m = mdates.DateFormatter("%b")
ax.xaxis.set_major_formatter(m)
ax.autoscale_view()
plt.show()
Kết quả đầu ra
Chương trình sẽ vẽ đường cong đa màu theo thời gian:

