# Constructing a Loop to Plot a Series of Graphs in Python

Oftentimes, we want to place charts of successive time points in parallel so it’s easy to observe patterns and traits. I was surprised that there are no clear and simple materials online to teach how to accomplish such a task using Python’s matplotlib drawing package.

I figured the following script to draw this kind of charts.

fig = plt.figure(figsize=(20, 8))
for i, day in enumerate(dates):
print i+1
length = len(hg_sector[(hg_sector.date == day) & (hg_sector.l1_id == num)])
x = hg_sector[(hg_sector.date == day) & (hg_sector.l1_id == num)].sort_values(‘ln_id’)[‘diverse’]
y = hg_sector[(hg_sector.date == day) & (hg_sector.l1_id == num)].sort_values(‘ln_id’)[‘pct_change’]
rng = np.random.RandomState(0)
colors = rng.rand(length)
sizes = hg_sector[(hg_sector.date == day) & (hg_sector.l1_id == num)].sort_values(‘ln_id’)[‘market_total_billion\$’]
axi = plt.scatter(x, y, c=colors, s=sizes, alpha=0.4, cmap=’viridis’)
title = ‘Sector %s Contains %s level 6 groups on %s’ %(num, length, day)
plt.title(title, size=15)

The key know-hows are:  1. use fig to set the size, space; 2. create variable ax – conceptually equating it to the plot position going through the loop; 3. create variable axi – conceptually is the actual plot element after going through the loop.

Another example script is

for i, res in enumerate([‘l’, ‘h’]):
m = Basemap(projection=’gnom’, lat_0=57.3, lon_0=-6.2,
width=90000, height=120000, resolution=res, ax=ax[i])
m.fillcontinents(color=”#FFDDCC”, lake_color=’#DDEEFF’)
m.drawmapboundary(fill_color=”#DDEEFF”)
m.drawcoastlines()
ax[i].set_title(“resolution='{0}'”.format(res));

And an example on using imshow for plotting the famous 64 handwriting digits:

fig, ax = plt.subplots(8, 8, figsize=(6, 6))
for i, axi in enumerate(ax.flat):
axi.imshow(digits.images[i], cmap=’binary’)
axi.set(xticks=[], yticks=[])

Or, applying a plot function:

#plot:
def density_plot(data):
plt.rcParams[‘font.sans-serif’]=[‘SimHei’]
plt.rcParams[‘axes.unicode_minus’]=False
p=data.plot(kind=’kde’,linewidth=2,subplots=True,sharex=False)
[p[i].set_ylabel(‘密度’) for i in range(5)]
[p[i].set_title(‘客户群%d’ %i) for i in range(5)]
plt.legend()
plt.show()
return plt
density_plot(data4)

This site uses Akismet to reduce spam. Learn how your comment data is processed.