BaRud
BaRud

Reputation: 3230

matplotlib dynamic number of subplot

I am trying to get a subplot using matplotlib, with number of subplots calculated in runtime (as pnum varies in the example below)

  pnum = len(args.m)
  f, (ax1, ax2) = plt.subplots(pnum, sharex=True, sharey=True)
  ax1.plot(x,ptp, "#757578",label="Total")
  ax2.fill_between(x,dxyp,facecolor="C0", label="$d_{xy}$")

This example, obviously, only work, when pnum=2. So, I need to do some thing else.

I have checked the accepted answer of this question, but this is plotting same thing in all the plots.

Upvotes: 2

Views: 3320

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

To create a dynamic number of subplots you may decide not to specify the axes individually, but as an axes array

pnum = len(args.m)
fig, ax_arr = plt.subplots(pnum, sharex=True, sharey=True)

ax_arr is then a numpy array. You can then do something for each axes in a loop.

for ax in ax_arr.flatten():
    ax.plot(...)

Upvotes: 2

Related Questions