Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ biểu đồ sự kiện chồng (stacked event duration) bằng Python Pandas

Để vẽ timeline sự kiện chồng (Gantt-like) từ DataFrame có cột xmin, xmax (datetime), dùng plt.hlines().

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo DataFrame với cột xmin, xmax kiểu datetime.
  • Vẽ đường ngang: plt.hlines(df.index, df.xmin, df.xmax, lw=5, colors='red').
  • Hiển thị bằng show().

Ví dụ

import pandas as pd
from datetime import datetime as dt
from matplotlib import pyplot as plt

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

df = pd.DataFrame(dict(xmin=[dt.strptime('1994-07-19', '%Y-%m-%d'), dt.strptime('2006-03-16', '%Y-%m-%d'), dt.strptime('1980-10-31', '%Y-%m-%d'), dt.strptime('1981-06-11', '%Y-%m-%d'), dt.strptime('2006-06-28', '%Y-%m-%d')], xmax=[dt.strptime('1998-06-30', '%Y-%m-%d'), dt.strptime('2007-01-24', '%Y-%m-%d'), dt.strptime('2007-07-31', '%Y-%m-%d'), dt.strptime('1990-08-01', '%Y-%m-%d'), dt.strptime('2007-01-24', '%Y-%m-%d')] ))
plt.hlines(df.index, df.xmin, df.xmax, lw=5, colors='red')
plt.show()

Kết quả

Vẽ biểu đồ sự kiện chồng (stacked event duration) bằng Python Pandas