Reputation: 2098
I make some subplots by using:
fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
Then, I would like to personalize the subplots, e.g., with:
plt.subplots_adjust(hspace = 0., wspace= 0.)
However, I would like to personalize the ticks as well, like removing the ticks and the labels for some of those subplots. How could I do that?
The problem is that, after the definition, ax is a numpy array: I don't know that much of it, what I know is that it is impossible to use attributes (like, ax[0].set_yticks([])
).
Upvotes: 0
Views: 852
Reputation: 74154
If you create a 2D array of plots, e.g. with:
>>> fig, axarray = plt.subplots(3, 4)
then axarray
is a 2D array of objects, with each element containing a matplotlib.axes.AxesSubplot
:
>>> axarray.shape
(3, 4)
The problem is that when you index axarray[0]
, you're actually indexing a whole row of that array, containing several axes:
>>> axarray[0].shape
(4,)
>>> type(axarray[0])
numpy.ndarray
However, if you address a single element in the array then you can set its attributes in the normal way:
>>> type(axarray[0,0])
matplotlib.axes.AxesSubplot
>>> axarray[0,0].set_title('Top left')
A quick way of setting the attributes of all of the axes in the array is to loop over a flat iterator on the axis array:
for ii,ax in enumerate(axarray.flat):
ax.set_title('Axis %i' %ii)
Another thing you can do is 'unpack' the axes in the array into a nested tuple of individual axis objects, although this gets a bit awkward when you're dealing with large numbers of rows/columns:
fig, ((ax1, ax2, ax3, ax4), (ax5, ax6, ax7, ax8), (ax9, ax10, ax11, ax12)) \
= plt.subplots(3,4)
Upvotes: 3
Reputation: 12234
When using this method:
fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
you have two choices, either call the elements of the array ax
like you have suggested (but you will need to use two indices or flatten it):
ax[0][0].plot(...
ax.flat[0].plot(...
this second line is useful if you loop over the plots. Or you can modify in the following way:
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
It will depend on your use case which is better, I typically call the array ax
if there is a chance I will change the number of subplot.
Upvotes: 1