Để vẽ hai chuỗi thời gian Pandas trên cùng biểu đồ với legend và trục Y thứ hai, 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 ndarray một chiều với nhãn trục (kể cả chuỗi thời gian).
- Tạo dataframe với danh sách cột.
- Vẽ cột A, B dùng dataframe plot().
- Lấy handles và labels cho legend dùng get_legend_handles_labels().
- Đặt legend trên hình dùng legend().
- Hiển thị hình dùng show().
Ví dụ
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ts = pd.Series(np.random.randn(10), index=pd.date_range('2021-04-10', periods=10))
df = pd.DataFrame(np.random.randn(10, 4), index=ts.index, columns=list('ABCD'))
ax1 = df.A.plot(color='red', label='Count')
ax2 = df.B.plot(color='yellow', secondary_y=True, label='Sum')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
plt.legend(h1+h2, l1+l2, loc=2)
plt.show()
Kết quả
