Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีพลอตเส้นหลายสีเมื่อแกน X เป็น Datetime Index ของ Pandas

ภาพรวม

เมื่อแกน X เป็น datetime index การพลอตเส้นที่สีเปลี่ยนตามค่า (multicolor line) ต้องใช้ LineCollection จาก matplotlib.collections

ขั้นตอนการทำงาน

  • กำหนดขนาดฟิกเกอร์และปรับ padding
  • สร้างข้อมูล datetime index และค่า y ด้วย numpy
  • สร้าง figure และ axes
  • แปลงวันที่เป็นตัวเลขด้วย mdates.date2num()
  • สร้าง segments สำหรับ LineCollection
  • กำหนด colormap (เช่น 'hot') และเพิ่ม collection ลง axes
  • ตั้งค่า locator และ formatter สำหรับแกน X ให้แสดงเดือน/วัน
  • ใช้ autoscale_view() และแสดงผล

ตัวอย่างโค้ด

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)
segments = np.concatenate([p[:-1], p[1:]], axis=1)

lc = c.LineCollection(segments, cmap="hot")
lc.set_array(xval)
ax.add_collection(lc)

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b"))
ax.autoscale_view()
plt.show()

ผลลัพธ์

กราฟเส้นที่สีเปลี่ยนจากเย็นไปร้อนตามลำดับเวลา

วิธีพลอตเส้นหลายสีเมื่อแกน X เป็น Datetime Index ของ Pandas วิธีพลอตเส้นหลายสีเมื่อแกน X เป็น Datetime Index ของ Pandas

คำอธิบายเพิ่มเติม

  • LineCollection เหมาะสำหรับพลอตเส้นหลายเส้นหรือเส้นที่มีสีเปลี่ยนได้
  • set_array() ใช้กำหนดค่าที่ map กับ colormap
  • DateFormatter("%b") แสดงชื่อเดือนย่อ (Jan, Feb, ...)