Issue
When I was using the subplot, and tried to use the following subplot to plot only one figure, it will give error:
AttributeError: 'AxesSubplot' object has no attribute 'flat'
fig, ax = plt.subplots(nrows=nrows, ncols=ncols,figsize=figsize)
for i, ax in enumerate(ax.flat):
ax.plot(X, Y, color='k')
How to solve this issue if I want to arbitrarily set the number of sub figures?How can I easily understand ax.flat
?
Solution
flat
is an attribute of numpy
arrays which returns an iterator. For example, if you have a 2d array like this:
import numpy as np
arr2d = np.arange(4).reshape(2, 2)
arr2d
# array([[0, 1],
# [2, 3]])
the flat
attribute is provided as a convenient way to iterate through this array as if it was a 1d array:
for value in arr2d.flat:
print(value)
# 0
# 1
# 2
# 3
You can also flatten the array with the flatten
method:
arr2d.flatten()
# array([0, 1, 2, 3])
So going back to your question, when you specify:
ncols
to 1 andnrows
to a value greater than 1 or the other way around, you get the axes in a 1d numpy array, in which case theflat
attribute returns the same array.- both
ncols
andnrows
to values greater than 1, you get the axes in a 2d array, in which case theflat
attribute returns the flattened array. - both
ncols
andnrows
to 1, you get the axes object, which doesn't have aflat
attribute.
So a possible solution would be to turn your ax
object into a numpy
array everytime:
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
ax = np.array(ax)
for i, axi in enumerate(ax.flat):
axi.plot(...)
Answered By - josemz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.