我有一个数据框,我试图在单轴上绘制它。它有 5 个不同的列,其中前 4 列是 y 轴,第 5 列是 x 轴。
我正在尝试根据数据框的列名称创建一个 for 循环,然后循环数据并将它们绘制成一张图。
下面是一个示例,其中“names”是包含数据框“df”的列标题的变量。
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()
输出:
关于python - 使用 python 中的 for 循环仅在一个轴上创建多个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71881514/