如何在python

时间:2018-06-06 01:21:28

标签: python function oop matplotlib

我正在尝试创建一个包含简单函数的模块,用于创建已经应用了一些常见格式的图。其中一些函数将应用于已存在的matplotlib对象,并将其他matplotlib对象返回到主程序。

第一段代码是我当前如何生成绘图的示例,它按原样运行。

# Include relevant python libraries
from matplotlib import pyplot as plt

# Define plot formatting
axesSize = [0, 0, 1, 1]
axesStyle = ({'facecolor':(0.95, 0.95, 0.95)})

gridStyle = ({'color':'k',
              'linestyle':':',
              'linewidth':1})

xString = "Independent Variable"
xLabelStyle = ({'fontsize':18,
                'color':'r'})

# Create figure and axes objects with appropriate style
figureHandle = plt.figure()
axesHandle = figureHandle.add_axes(axesSize, **axesStyle)

axesHandle.grid(**gridStyle)
axesHandle.set_xlabel(xString, **xLabelStyle)

我想创建一个将add_axes()命令与grid()和set_xlabel()命令结合起来的函数。作为第一次尝试,忽略所有样式,我在NTPlotTools.py模块中提出了以下功能。

def CreateAxes(figureHandle, **kwargs):
    axesHandle = figureHandle.add_axes()
    return axesHandle

调用函数的脚本如下所示:

# Include relevant python libraries
from matplotlib import pyplot as plt
from importlib.machinery import SourceFileLoader as fileLoad

# Include module with my functions
pathName = "/absolute/file/path/NTPlotTools.py"
moduleName = "NTPlotTools.py"
pt = fileLoad(moduleName, pathName).load_module()

# Define plot formatting
gridStyle = ({'color':'k',
              'linestyle':':',
              'linewidth':1})

# Create figure and axes objects with appropriate style
figureHandle = plt.figure()
axesHandle = pt.CreateAxes(figureHandle)

axesHandle.grid(**gridStyle)

但是,运行主代码时出现以下错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-73802a54b21a> in <module>()
     17 axesHandle = pt.CreateAxes(figureHandle)
     18 
---> 19 axesHandle.grid(**gridStyle)

AttributeError: 'NoneType' object has no attribute 'grid'

这告诉我,axesHandle不是matplotlib轴对象,并且通过扩展,CreateAxes()函数调用没有返回matplotlib轴对象。是否有将matplotlib对象传递给函数的功能?

1 个答案:

答案 0 :(得分:0)

你快到了。问题出在这条线上。

def CreateAxes(figureHandle, **kwargs)
    axesHandle = figureHandle.add_axes() # Here
    return axesHandle

source code add_axes方法看起来如下

def add_axes(self, *args, **kwargs):
    if not len(args):
       return
    # rest of the code ...

因此,当您在没有任何参数的情况下调用figureHandle.add_axes()时,argskwrags都将为空。如果args为空,则从源代码add_axes方法返回None。因此,此None值会分配给axesHandle,当您尝试调用axesHandle.grid(**gridStyle)时,您将获得

AttributeError: 'NoneType' object has no attribute 'grid'

<强> 实施例

>>> def my_demo_fun(*args, **kwrags):
...     if not len(args):
...          return
...     return args
...
>>> print(my_demo_fun())
None
>>> print(my_demo_fun(1, 2))
(1, 2)

因此,通过将参数传递给add_axes方法来重写函数。

def create_axes(figure_handle, **kwargs):
    axes_handle = figure_handle.add_axes(axes_size, **axes_style) 
    return axes_handle