Do not call plt.figure
more than once, as each call creates a new figure (roughly speaking, window).
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
'Paris', 'New York', 'New York', 'London', 'Paris'],
'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}
df = pd.DataFrame(d)
fig, ax = plt.subplots(figsize=(5, 4)) # 1
df.groupby(['City']).plot(kind='scatter', x='Age', y='Weight',
ax=ax, # 2
color=['red', 'blue', 'green'])
plt.show()
plt.subplots
returns a figure,fig
and an axes,ax
.- If you pass
ax=ax
to Panda's plot method, then all the plots will show up on the same axis.
To make a separate figure for each city:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
'Paris', 'New York', 'New York', 'London', 'Paris'],
'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}
df = pd.DataFrame(d)
groups = df.groupby(['City'])
for city, grp in groups: # 1
fig, ax = plt.subplots(figsize=(5, 4))
grp.plot(kind='scatter', x='Age', y='Weight', # 2
ax=ax)
plt.show()
- This is perhaps all you were missing. When you iterate over a GroupBy object, it returns a 2-tuple: the groupby key and the sub-DataFrame.
- Use
grp
, the sub-DataFrame instead ofdf
inside the for-loop.