2

Is it possible to automatically generate multiple subplots in matplotlib? An example of the process I want to automate is:

import matplotlib.pyplot as plt
figure = plt.figure()
ax1 = figure.add_subplot(2, 3, 1)
ax2 = figure.add_subplot(2, 3, 2)
ax3 = figure.add_subplot(2, 3, 3)
ax4 = figure.add_subplot(2, 3, 4)
ax5 = figure.add_subplot(2, 3, 5)
ax6 = figure.add_subplot(2, 3, 6)

The subplots need unique names, as this will allow me to do stuff like:

for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
    ax.set_title("example")

Many thanks.

Addition: Are there any functions that automate the generation of multiple subplots? What if I needed to repeat the above process 100 times? Would I have to type out every ax1 to ax100?

2
  • by automatically generate, what do you mean? could you be more specific? Commented Nov 28, 2014 at 9:12
  • to generate the above 6 subplots, I believe you can only minimize the code by adding in more for loops for your remaining title,legend etc. Commented Nov 28, 2014 at 9:15

1 Answer 1

6

You can use:

fig, axs = plt.subplots(2,3)

axs will be an array containing the subplots.

Or unpack the array instantly:

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2,3)
Sign up to request clarification or add additional context in comments.

1 Comment

Should the second option should be fig, ([ax1, ax2, ax3], [ax4, ax5, ax6]) = plt.subplots(2,3) or something similar, as axs is a 2x3 array?

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.