社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Drew Stephenson • 3 年前 • 1266 次点击  

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

我试图根据数据框的列名创建一个for循环,循环数据并将其绘制成一个图形。

下面是一个示例,其中“names”是包含dataframe“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条不同的线?谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131996
 
1266 次点击  
文章 [ 1 ]  |  最新文章 3 年前
mozway
Reply   •   1 楼
mozway    3 年前

假设这个例子:

   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