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

วิธีพลอตกราฟ Time Series ด้วย Seaborn หรือ Plotly

ภาพรวม

Time Series plot แสดงข้อมูลตามลำดับเวลา ใช้ Seaborn สำหรับ static plot หรือ Plotly สำหรับ interactive plot

ตัวอย่างด้วย Seaborn

import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

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

df = pd.DataFrame(dict(
    time=list(pd.date_range("2021-01-01 12:00:00", periods=10, freq="30min")),
    speed=np.linspace(1, 10, 10)
))

ax = sns.lineplot(x="time", y="speed", data=df)
ax.tick_params(rotation=45)
plt.show()

ผลลัพธ์ Seaborn

Line plot แสดงความเร็วตามเวลา ปรับการหมุน label แกน X

วิธีพลอตกราฟ Time Series ด้วย Seaborn หรือ Plotly วิธีพลอตกราฟ Time Series ด้วย Seaborn หรือ Plotly

ตัวอย่างด้วย Plotly (เพิ่มเติม)

import plotly.express as px

fig = px.line(df, x="time", y="speed", title="Speed over Time")
fig.show()

เปรียบเทียบ

คำแนะนำ

  • รายงาน Static/Journal ใช้ Seaborn/Matplotlib
  • Dashboard/Web App ใช้ Plotly
  • Seaborn: sns.lineplot() จัดการ datetime index อัตโนมัติ
คุณสมบัติSeaborn/MatplotlibPlotly
Interactiveไม่ใช่ (zoom, hover, pan)
สวยงามทันทีปานกลางดีมาก
Export staticง่ายต้อง kaleido/orca
Web embeddingต้องแปลงHTML/JS ตรงๆ