Reputation: 471
How can I create one plot for this loop?
I want to create some subplots according to i
values taken from the loop. Do I need to create a new For/Loop
which goes to each subplot? How can I do it?. This is my code:
fig, axes = plt.subplots(nrows=4, ncols=3)
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Main plots')
for i in range(1,13):
month = [i]
DF_sub = DF[DF['months'].isin(month)]
out = pd.cut(DF_sub['new'], 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.title('Subplot -' + str(i))
Up to now, I just get the last one, but I am missing the previos i
-s values from the loop
Upvotes: 0
Views: 679
Reputation: 4471
You need to pass the ax
parameter to plot.bar
to specify on which of your axes
, returned from plt.subplots
, the bar chart should be plotted, i.e.:
fig, axes = plt.subplots(nrows=4, ncols=3)
fig.subplots_adjust(hspace=0.5)
fig.suptitle('Main plots')
for i in range(1,13):
month = [i]
ax = axes[i - 1]
DF_sub = DF[DF['months'].isin(month)]
out = pd.cut(DF_sub['new'], bins=[0, 0.25, 0.5, 0.75, 1], include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True)
out_norm.plot.bar(rot=0, color="b", figsize=(6,4), ax=ax)
plt.title('Subplot -' + str(i))
If you don't pass the ax
parameter, the bar chart will automatically be plotted on the currently active axis, which is the one most recently created unless set otherwise.
Upvotes: 1