我试图创建一个模块,其中包含一些简单的函数,用于创建已经应用了一些常见格式的绘图。其中一些函数将应用于已经存在的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\u axes()命令与grid()和set\u 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 axes对象,而且通过扩展,CreateAxes()函数调用没有返回matplotlib axes对象。向函数传递matplotlib对象或从函数传递matplotlib对象有什么诀窍吗?你知道吗
你就快到了。问题出在这条线上。你知道吗
在^{} 中,
add_axes
方法如下所示因此,当调用
figureHandle.add_axes()
而不使用任何参数时,args
和kwrags
都将为空。从源代码中,如果args
为空add_axes
方法返回None
。因此,这个None
值被分配给axesHandle
,当您尝试调用axesHandle.grid(**gridStyle)
时,您将得到示例
因此,通过向
add_axes
方法传递参数来重新编写函数。你知道吗相关问题 更多 >
编程相关推荐