2

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.

1
  • So how would you determine what should be plotted to each subplot if not by using a loop, like in the linked question? Commented May 24, 2017 at 13:18

1 Answer 1

2

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(...)
Sign up to request clarification or add additional context in comments.

1 Comment

where ax_arr is a list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.