Reputation: 21408
The code
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
print type(ax)
gives the output
<class 'matplotlib.axes.AxesSubplot'>
Then the code
import matplotlib.axes
matplotlib.axes.AxesSubplot
raises the exception
AttributeError: 'module' object has no attribute 'AxesSubplot'
To summarize, there is a class matplotlib.axes.AxesSubplot
, but the module matplotlib.axes
has no attribute AxesSubplot
. What on earth is going on?
I'm using Matplotlib 1.1.0 and Python 2.7.3.
Upvotes: 33
Views: 23136
Reputation: 329
Another way to see what DSM said:
In [1]: from matplotlib import pyplot as plt
In [2]: type(plt.gca()).__mro__
Out[2]:
(matplotlib.axes._subplots.AxesSubplot,
matplotlib.axes._subplots.SubplotBase,
matplotlib.axes._axes.Axes,
matplotlib.axes._base._AxesBase,
matplotlib.artist.Artist,
object)
with the dunder method resolution order you can find all the inheritances of some class.
Upvotes: 1
Reputation: 353139
Heh. That's because there is no AxesSubplot
class.. until one is needed, when one is built from SubplotBase
. This is done by some magic in axes.py
:
def subplot_class_factory(axes_class=None):
# This makes a new class that inherits from SubplotBase and the
# given axes_class (which is assumed to be a subclass of Axes).
# This is perhaps a little bit roundabout to make a new class on
# the fly like this, but it means that a new Subplot class does
# not have to be created for every type of Axes.
if axes_class is None:
axes_class = Axes
new_class = _subplot_classes.get(axes_class)
if new_class is None:
new_class = new.classobj("%sSubplot" % (axes_class.__name__),
(SubplotBase, axes_class),
{'_axes_class': axes_class})
_subplot_classes[axes_class] = new_class
return new_class
So it's made on the fly, but it's a subclass of SubplotBase
:
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> print type(ax)
<class 'matplotlib.axes.AxesSubplot'>
>>> b = type(ax)
>>> import matplotlib.axes
>>> issubclass(b, matplotlib.axes.SubplotBase)
True
Upvotes: 35