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))
fig.subplots_adjust(hspace=0.2, wspace=0.1)
for i, day in enumerate(dates):
print i+1
ax = fig.add_subplot(2, 3, i+1)
length = len(hg_sector[( == day) & (hg_sector.l1_id == num)])
x = hg_sector[( == day) & (hg_sector.l1_id == num)].sort_values(‘ln_id’)[‘diverse’]
y = hg_sector[( == day) & (hg_sector.l1_id == num)].sort_values(‘ln_id’)[‘pct_change’]
rng = np.random.RandomState(0)
colors = rng.rand(length)
sizes = hg_sector[( == 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)

sector three dimension

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

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:

def density_plot(data):
[p[i].set_ylabel(‘密度’) for i in range(5)]
[p[i].set_title(‘客户群%d’ %i) for i in range(5)]
return plt

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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