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

Vẽ nhiều DataFrame chuỗi thời gian vào một biểu đồ dùng Pandas (Matplotlib)

Để vẽ nhiều DataFrame chuỗi thời gian vào một biểu đồ dùng Pandas, ta thực hiện:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm giữa và xung quanh subplots.
  • Tạo DataFrame Pandas với chuỗi thời gian.
  • Đặt chỉ số chuỗi thời gian cho biểu đồ.
  • Vẽ rupees và dollar trên đồ thị.
  • Hiển thị hình dùng show().

Ví dụ

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, dates

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

df = pd.DataFrame(dict(date=list(pd.date_range("2021-01-01", periods=10)),
                       rupees=np.linspace(1, 10, 10),
                       dollar=np.linspace(10, 20, 10)))
df.set_index(pd.to_datetime(df.date), drop=True).plot()
df = df.set_index(pd.to_datetime(df.date), drop=True)
df.rupees.plot(grid=True, label="rupees", legend=True)
df.dollar.plot(secondary_y=True, label="dollar", legend=True)
plt.show()

Kết quả

Vẽ nhiều DataFrame chuỗi thời gian vào một biểu đồ dùng Pandas (Matplotlib)