There is a class matplotlib.axes.AxesSubplot, but the module matplotlib.axes has no attribute AxesSubplot


Question

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.

1
20
7/27/2012 3:15:42 PM

Accepted Answer

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
22
7/27/2012 3:19:13 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon