LeafTeaNeko
LeafTeaNeko

Reputation: 113

Iterating over a dataframe and plotting sections of the dataframe on the same plot

I'm looping through a dataframe with clusters of entries and I want to plot each iteration of the dataframe slice.

I've tried using ax = plot(iter 1) with ax = ax for plotting "iter 2" but that doesn't help. What would be the best way to plot slice over slice of the same df?

For example, I want to plot "iter 1" and then plot "iter 2" and "iter 3" over it.

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

My entire dataframe looks something like this:

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

Upvotes: 1

Views: 60

Answers (1)

tdy
tdy

Reputation: 41327

Either use plt.plot, which automatically reuses the existing axes:

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

plt.xlabel('Dis')
plt.ylabel('Rate')
plt.legend()

Or use ax.plot by first creating ax via plt.subplots:

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()

Or use sns.lineplot with hue='S/N':

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

(Note that I slightly modified some 999 values since they were identical to 332's values.)

Upvotes: 1

Related Questions