【问题标题】:Iterating over a dataframe and plotting sections of the dataframe on the same plot迭代数据框并在同一图上绘制数据框的部分
【发布时间】:2022-01-11 05:13:07
【问题描述】:

我正在循环遍历具有条目集群的数据帧,并且我想绘制数据帧切片的每次迭代。

我尝试使用 ax = plot(iter 1)ax = ax 来绘制“iter 2”,但这没有帮助。在同一 df 的切片上绘制切片的最佳方法是什么?

例如,我想绘制“iter 1”,然后在其上绘制“iter 2”和“iter 3”。

for loop through dataframe: 0
0     332    4.6030    91.204062
3     332    9.1985    76.212943
6     332   14.4405    77.664282
9     332   20.2005    76.725955
12    332   25.4780    31.597510
15    332   30.6670    74.096975

for loop through dataframe: 1
1     445    5.4280    60.233917
4     445    9.7345    31.902842
7     445   14.6015    36.261851
10    445   19.8630    40.705467
13    445   24.9050     4.897008
16    445   30.0550    35.217889

for loop through dataframe: 2
2     999    4.6030    91.474156
5     999    9.1985    76.212943
8     999   14.4405    77.664282
11    999   20.2005    76.725955
14    999   25.4780    31.597510
17    999   30.6670    74.096975

我的整个数据框看起来像这样:

0     332    4.6030    91.204062
3     332    9.1985    76.212943
6     332   14.4405    77.664282
9     332   20.2005    76.725955
12    332   25.4780    31.597510
15    332   30.6670    74.096975
1     445    5.4280    60.233917
4     445    9.7345    31.902842
7     445   14.6015    36.261851
10    445   19.8630    40.705467
13    445   24.9050     4.897008
16    445   30.0550    35.217889
2     999    4.6030    91.474156
5     999    9.1985    76.212943
8     999   14.4405    77.664282
11    999   20.2005    76.725955
14    999   25.4780    31.597510
17    999   30.6670    74.096975

【问题讨论】:

    标签: python python-3.x pandas dataframe matplotlib


    【解决方案1】:

    要么使用 plt.plot,它会自动重用现有的坐标区:

    for label, data in df.groupby('S/N'):
        plt.plot(data['Dis'], data['Rate'], label=label)
    
    plt.xlabel('Dis')
    plt.ylabel('Rate')
    plt.legend()
    

    或者使用ax.plot,首先通过plt.subplots创建ax

    fig, ax = plt.subplots()
    
    for label, data in df.groupby('S/N'):
        ax.plot(data['Dis'], data['Rate'], label=label)
    
    ax.set(xlabel='Dis', ylabel='Rate')
    plt.legend()
    

    或者使用 sns.lineplothue='S/N':

    import seaborn as sns
    sns.lineplot(x='Dis', y='Rate', hue='S/N', data=df)
    

    (请注意,我稍微修改了一些 999 值,因为它们与 332 的值相同。)

    【讨论】:

    • 再次感谢您,Tdy!当我看到适当的列名时我很惊讶,但后来我意识到你也回答了我之前的问题。
    猜你喜欢
    • 2021-11-21
    • 2015-12-18
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2021-12-09
    • 2018-11-30
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多