2

I try to set title for subplots from array of data.

What I expect to have is that Title-1, Title-2 ... and so on for (00, 01 , 10 and 11) locations in the figure.

So I did;

import matplotlib.pyplot as plt    

title = [1,2,3,4]

fig, ax = plt.subplots(2, 2, figsize=(6, 8))  

    for i in range(len(ax)): 
        for j in range(len(ax[i])):

            for k in title:
            #    print (k)
                ax[i,j].set_title('Title-' + str(k))

But only getting Title-4. How can I fix this issue ? Thx

enter image description here

Alexander
  • 4,527
  • 5
  • 51
  • 98

3 Answers3

5

One method use flatten and enumerate:

import matplotlib.pyplot as plt    

title = [1,2,3,4]

fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
flat_ax = ax.flatten()

for n, ax in enumerate(flat_ax):
    ax.set_title(f'Title-{title[n]}')

Output:

enter image description here

Another option is to use iter with flatten:

import matplotlib.pyplot as plt    

title = [1,2,3,4]
ititle = iter(title)

fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
flat_ax = ax.flatten()

for ax in flat_ax:
    ax.set_title(f'Title-{next(ititle)}')

Also, note I am using f-string which requires python 3.6+

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
2

This happens because you are doing repeated assignments of title looping from 1 up to 4 for each combination of i, j. You need to refactor your code in a way it does only one assignment for each i and j:

for i in range(len(ax)):
    for j in range(len(ax[i])):
        ax[i,j].set_title('Title-' + str(1+2*i+j))

You might also like to make a dictionary

codes = {(0,0):1, (0,1):2, (1,0):3, (1,1):4}

and replace last line by

ax[i,j].set_title('Title-' + str(codes[i,j]))
mathfux
  • 5,759
  • 1
  • 14
  • 34
  • Thanks! but What if I have `title = [111,223,1233,423]` type title ? the first solution would not apply! secondly, if I have dozens of titles it becomes a little bit troublesome to create a dictionary for each of them! – Alexander Dec 29 '19 at 06:08
  • I didn't know there's `flatten` method implemented for this purpose in matplotlib – mathfux Dec 29 '19 at 06:13
  • 1
    @mathfux `flatten` is a numpy array method, when you have more than 1 axes defined with `plt.subplots` what is returned is numpy array of axes. – Scott Boston Dec 29 '19 at 06:31
1

You can use the function ndindex to iterate over the N-dimensional index of the array:

fig, ax = plt.subplots(2, 2, figsize=(6, 8))
titles = [1,2,3,4]

for idx, t in zip(np.ndindex(ax.shape), titles):
    ax[idx].set_title(f'Title {t}')
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73