有一个类matplotlib.axes.AxesSubplot,但模块matplotlib.axes没有属性AxesSubplot

Joh*_*åde 20 python matplotlib

代码

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
print type(ax)
Run Code Online (Sandbox Code Playgroud)

给出输出

<class 'matplotlib.axes.AxesSubplot'>
Run Code Online (Sandbox Code Playgroud)

然后是代码

import matplotlib.axes
matplotlib.axes.AxesSubplot
Run Code Online (Sandbox Code Playgroud)

引发例外

AttributeError: 'module' object has no attribute 'AxesSubplot'
Run Code Online (Sandbox Code Playgroud)

总而言之,有一个类matplotlib.axes.AxesSubplot,但模块matplotlib.axes没有属性AxesSubplot.到底是怎么回事?

我正在使用Matplotlib 1.1.0和Python 2.7.3.

DSM*_*DSM 22

嘿.这是因为有AxesSubplot类..直到需要一个,当一个人从建SubplotBase.这是由一些魔术完成的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
Run Code Online (Sandbox Code Playgroud)

所以它是在飞行中制作的,但它是以下的子类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
Run Code Online (Sandbox Code Playgroud)

  • 它*是*创建的,但它不是存储在模块级别.查看`matplotlib.axes._subplot_classes`:你应该看到`{matplotlib.axes.Axes:matplotlib.axes.AxesSubplot}`.请注意,在工厂函数中,`new_class`被添加到`_subplot_classes`字典中. (4认同)