Destaneon
Destaneon

Reputation: 55

Matplotlib xlabel plotting error (IndexError: list index out of range)

I'm plotting several 16 images using matplotlib and labeling their name using the column name from which this images were extracted. I'm running into an issue where the index of the plots and their label is not matching.

here is the worflow I have so far.

names = [(i) for i in (columns)]
names

the list of the column names is:

['value__longest_strike_above_mean',
 'value__longest_strike_below_mean',
 'value__maximum',
 'value__mean',
 'value__mean_abs_change',
 'value__mean_change',
 'value__median',
 'value__minimum',
 'value__number_cwt_peaks__n_12',
 'value__number_cwt_peaks__n_6',
 'value__quantile__q_0.05',
 'value__quantile__q_0.15',
 'value__quantile__q_0.85',
 'value__quantile__q_0.95',
 'value__skewness',
 'value__sum_values'] 

There are 16 names that will be assigned to the plots below.

for i in range(0,16):
    img = f2Array[:,:,i]  
    i = i+1
    plt.subplot(4,4,i)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap="gist_earth")
    plt.xlabel((names[i]), fontsize=10)

plotting this way gave me the following error

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-284-299c4a617b63> in <module>()
     13     plt.yticks([])
     14     plt.imshow(img, cmap="gist_earth")
---> 15     plt.xlabel((names[i]), fontsize=10)
     16 
     17 

IndexError: list index out of range

]

The indexing of the names started from 1 instead of 0 which distorted the labeling. The very last plot also doesn't have a name.

Any idea on how to improve the labeling?

Upvotes: 1

Views: 2229

Answers (2)

Kamil Niski
Kamil Niski

Reputation: 4765

You should refactor your code a bit:

for i, name in enumerate(names):
    img = f2Array[:,:,i]  
    plt.subplot(4,4,i + 1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap="gist_earth")
    plt.xlabel((name), fontsize=10)

Upvotes: 2

Banghua Zhao
Banghua Zhao

Reputation: 1556

The index of subplot(nrows, ncols, index, **kwargs) start at 1. So just remove i=i+1 and use plt.subplot(4,4,i+1). Try this:

for i in range(0,16):
    img = f2Array[:,:,i]  
    plt.subplot(4,4,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap="gist_earth")
    plt.xlabel((names[i]), fontsize=10)

Upvotes: 1

Related Questions