您需要在
axes
对象,即
axes[0,0]
在子图中2x2网格的第一行和第一列的轴上绘制。
编辑
添加日期作为x轴
import matplotlib.pyplot as plt
import pandas as pd
data = {
"Date": [2000,2001,2000,2001,2000,2001,2000,2001,2000,2001,2000,2001,2000,2001,2000,2001,],
"Main": ["A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B",],
"Sub": ["A1","A1","A2","A2","A3","A3","A4","A4","B1","B1","B2","B2","B3","B3","B4","B4",],
"col1": [1, 2, 4, 5, 1, 2, 6, 4, 8, 5, 7, 2, 4, 5, 1, 2],
"col2": [5, 6, 1, 4, 5, 4, 5, 1, 5, 4, 5, 6, 4, 5, 8, 4],
}
df = pd.DataFrame(data)
df_M = [x for _, x in df.groupby(["Main"])]
for groupName, groupdf in df.groupby(["Main"]):
fig, axes = plt.subplots(
nrows=2, ncols=2, figsize=(12, 6), sharex=True, linewidth=1, edgecolor="black"
)
for idx, (subGroupName, subGroupdf) in enumerate(groupdf.groupby(["Sub"])):
row = 0 if idx < 2 else 1
col = idx % 2
for plottingCol in subGroupdf.columns.values[3:5]:
axes[row, col].plot(subGroupdf.Date, subGroupdf[plottingCol])
plt.show()