Loop through arrays in dataframe and plot by group

Viewed 314

I have a dataframe that contains X & Y position data and has 3 grouping variables:

  1. obsScenario (0, 1 or 2)
  2. startPos (1 or 2)
  3. targetPos (1, 2, or 3).

Thus there are 18 combinations of these grouping variables: 3 x 2 x 3

The X and Y data is approx 300-500 data points in length per participant (it varies).

The dataframe looks like this:

              X         Y  participantNum  obsScenario  startPos  targetPos
0    -16.000000  5.000000         6432024            0         1          1
1    -16.000000  5.000000         6432024            0         1          1
2    -15.833450  5.000000         6432024            0         1          1
3    -15.667200  5.000000         6432024            0         1          1
4    -15.500100  5.000000         6432024            0         1          1
        ...       ...             ...          ...       ...        ...
2185  -1.572058 -3.982638         7830381            2         2          2
2186  -1.406996 -3.958967         7830381            2         2          2
2187  -1.242231 -3.935339         7830381            2         2          2
2188  -1.077516 -3.911718         7830381            2         2          2
2189  -0.912604 -3.888069         7830381            2         2          2

I need to plot the X, Y data separately for each of these 18 combinations.

Im trying to use something like this, but this just plots all the XY trajectories on the same plot:

for aid, grp in df.groupby(['obsScenario', 'startPos', 'targetPos']):
    plt.plot(grp[0].values, grp[1].values) 
plt.show() 

And using something like this doesnt take the different combinations of grouping variables into account:

fig, axs = plt.subplots(nrows=3, ncols=6)

for ax in axs.flat:
    plotxy(ax,x,y)
1 Answers

This does what I was looking for:

fig, axs = plt.subplots(6,3)
grp = df.groupby(['obsScenario', 'startPos', 'targetPos'])
for (name, df), ax in zip(grp, axs.flat):
    df.plot(x='X',y='Y', ax=ax)
Related