ในการพล็อตเส้นหลากสีหากแกน X เป็นดัชนีวันที่และเวลาของ Pandas เราสามารถทำตามขั้นตอนต่อไปนี้ -
- กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
- สร้างจุดข้อมูล d, y และ s โดยใช้ numpy
- สร้างร่างและชุดแผนย่อย
- รับจุดข้อมูล xval, p และ s โดยใช้ numpy
- รับอินสแตนซ์คอลเลกชั่นไลน์ด้วย colormap ยอดนิยมและจุดข้อมูล
- ตั้งค่าตัวระบุตำแหน่งแกนหลักและรอง และตั้งค่าตัวจัดรูปแบบแกน
- ปรับขนาดขีดจำกัดการดูอัตโนมัติโดยใช้ขีดจำกัดข้อมูล
- หากต้องการแสดงรูป ให้ใช้ show() วิธีการ
ตัวอย่าง
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() ผลลัพธ์
มันจะสร้างผลลัพธ์ต่อไปนี้
