在 python 中使用 for 循环仅在一个轴上创建多个绘图

Creating multiple plots in only one axes using a for loop in python

我有一个数据框,我试图在单个轴上绘制。它有 5 个不同的列,其中前 4 列是 y-axis,第 5 列是 x-axis。

我正在尝试根据数据框的列名创建一个 for 循环并循环数据并将它们绘制成一个图形。

下面是一个示例,其中“names”是包含数据框“df”的列 headers 的变量。

df = pd.DataFrame(data) # Column heads contains {"A" "B" "C" "D" "X"}
               
names = []
for col in df.columns:
    names.append(col)

del names[-1]

for head in names:
    fig,ax1 = plt.subplots(1)
    x = df["X"]
    y = df[head]
    
    ax1.plot(x, y)

plt.show()

但是,这似乎在 4 个不同的图形中绘制了多个图形,因此在 4 个独立的轴上绘制了多个图形。我该如何调整代码,使其只输出一个带有 4 条不同线的单轴图形?谢谢

假设这个例子:

   y1  y2  y3  y4   x
0   0   4   8  12  16
1   1   5   9  13  17
2   2   6  10  14  18
3   3   7  11  15  19

你可以使用:

import matplotlib.pyplot as plt
f, axes = plt.subplots(nrows=2, ncols=2)

for i, col in enumerate(df.columns[:-1]):
    ax = axes.flat[i]
    ax.plot(df['x'], df[col])
    ax.set_title(col)

输出:

只有一个地块:
df.set_index('x').plot()

或循环:

ax = plt.subplot()
for name, series in df.set_index('x').items():
    ax.plot(series, label=name)
ax.legend()

输出: