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

วิธีพล็อต Time Series พร้อม Confidence Intervals ใน Python

การพล็อต Time Series พร้อมช่วงเชื่อมั่น

ใช้ rolling mean และ rolling std ของ pandas คำนวณ confidence intervals

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้าง time series array
  • กำหนด n_steps สำหรับ window size
  • คำนวณ mean และ standard deviation ด้วย rolling window
  • คำนวณ upper/lower bounds (mean ± 2*std)
  • พล็อตเส้น mean ด้วย plot()
  • เติมพื้นที่ confidence interval ด้วย fill_between()
  • แสดงผลด้วย show()

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

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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

time_series_array = np.sin(np.linspace(-np.pi, np.pi, 400)) + np.random.rand(400)
n_steps = 15

time_series_df = pd.DataFrame(time_series_array)
line = time_series_df.rolling(n_steps).mean()
line_deviation = 2 * time_series_df.rolling(n_steps).std()

under_line = (line - line_deviation)[0]
over_line = (line + line_deviation)[0]

plt.plot(line, linewidth=2)
plt.fill_between(line_deviation.index, under_line, over_line, color='red', alpha=.3)
plt.show()

คำอธิบาย

fill_between() สร้างพื้นที่เฉดสีระหว่าง upper และ lower bounds