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

标签 python matplotlib

我有一个数据框,我试图在单轴上绘制它。它有 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)

输出:

pure matplotlib

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

或者使用循环:

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

输出:

single plot

关于python - 使用 python 中的 for 循环仅在一个轴上创建多个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71881514/

相关文章:

python - 替换已弃用的 tsplot

python - Seaborn 多轴图将不同颜色分配给相同/共享类别色调

python /matplotlib : create graph with changing background colors

python - 在嵌入式绘图图表上启用滚轮缩放

Python "is not None"返回无

Python 多进程共享内存与使用参数

python - 在后台运行 shell 命令并使用 python 将 stdout 通过管道传输到日志文件

python - 为什么我用 matplotlib.imshow 绘制的 matplotlib 2D 直方图/热图与我的轴不匹配?

python - 为什么在 seaborn pairplot 的 kde 子图中没有显示颜色?

python - 无法抓取所有评论