-1

I have a dataframe that looks like the below

univ  date            ms      cs
 C    11/01/1977      0.2     0.1
 C    11/02/1977      0.3     0.4
 B    11/01/1977      0.6     -0.1
 B    11/02/1977      0.55    -0.5
 A    11/01/1977      0.23    0.2
 A    11/02/1977      0.12    0.15
 etc

This is what I currently have

fig, axes = plt.subplots(1, 3, figsize=(15, 5))

for (universe, group), ax in zip(df.groupby([df.univ]), axes.flatten()):
    group.plot(x='ms', y='cs', kind='scatter', ax=ax, title=universe)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)

This produces 3 scatter plots, with limits from 0 to 1. What I would like to do is keep the order of the plots titled as C, B, A, such that it gets ordered by A,B,C.

Thanks for your help!

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
qfd
  • 778
  • 2
  • 10
  • 24

1 Answers1

5

The problem is with the groupby which returns the items in sorted order by default. Just set the flag sort=False.

for (universe, group), ax in zip(df.groupby([df.univ], sort=False), axes.flatten()):
    group.plot(x='ms', y='cs', kind='scatter', ax=ax, title=universe)
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)

You could also return them in any order you desired.

gb = df.groupby('univ')
desired_order = ('B', 'A', 'C')
for (universe, group), ax in zip(((u, gb.get_group(u)) for u in desired_order), 
                                 axes.flatten()):
    ...

And btw, you should only have one question per post.

Alexander
  • 105,104
  • 32
  • 201
  • 196