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

后端 未结 2 842
长情又很酷
长情又很酷 2020-12-09 08:52

The code

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
print type(ax)

gives the output



        
相关标签:
2条回答
  • 2020-12-09 09:43

    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.

    0 讨论(0)
  • 2020-12-09 09:47

    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
    
    0 讨论(0)
提交回复
热议问题