Loop for subplot

Viewed 197

I have been dealing with this for several days. I have a loop to get info by month. I try to put them in a just one plot (subplot 1 = month 1, subplot 2 = month 2, and so on), however I get the last month in every subplot. What am I missing?

enter image description here

My code is:

import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)

plt.figure(0)
for m in range(1,13):
  for i in range(4):
    for j in range(3):
      ax = plt.subplot2grid((4,3), (i,j))
      DF_sub = DF[DF['months'] == m]
      out = pd.cut(DF_sub['trip'], bins=[0, 0.25, 0.5, 0.75, 1], include_lowest=True)
      out_norm = out.value_counts(sort=False, normalize=True)
      ax = out_norm.plot.bar(rot=0, color="b", figsize=(6,4))
      plt.xticks([])
      plt.title('Month-' + str(m))
plt.show()
1 Answers

You iterated through months (1 to 12), but within each month, you again iterate though i and j which means you are repeating something is plotting over and over again.

What you can do is iterate from 0 to 11, define the months and the position of the plot within each iteration. First some data:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)
DF = pd.DataFrame({"months":np.random.choice(np.arange(1,13),100),
                   "trip": np.random.uniform(size=100)
                  })

Then the plot as defined, most likely you don't need the labels:

fig, axs = plt.subplots(4, 3)
fig.tight_layout()
months = np.arange(1,13)
labels= ['bin1','bin2','bin3','bin4']
bins = [0, 0.25, 0.5, 0.75, 1]
for m in range(len(months)):
    i = m % 4
    j = int(m/4)   
    DF_sub = DF[DF['months'] == months[m]]
    out = pd.cut(DF_sub['trip'], bins=bins,
    labels=labels,include_lowest=True)
    out_norm = out.value_counts(sort=False, normalize=True)
    ax = axs[i,j] 
    ax.bar(x=labels,height=np.array(out_norm))
    ax.title.set_text('Month-' + str(months[m]))
    ax.set_xticks([])
plt.show()

enter image description here

A quick alternative is to use seaborn:

import seaborn as sns
DF['bins'] = pd.cut(DF['trip'], bins=bins,labels=labels,include_lowest=True)
counts = pd.crosstab(DF.months,DF.bins,normalize='index')
counts = counts.unstack().reset_index().rename(columns={0:"value"})
g = sns.FacetGrid(counts, col="months",aspect=.7,col_wrap=3)
g.map(sns.barplot, "bins", "value")

![enter image description here

Related