简体   繁体   English

如何在python中的函数之间传递/返回matplotlib对象

[英]How to pass/return matplotlib objects to/from functions in python

I am trying to create a module that contains simple functions for creating plots with some common formatting already applied to them. 我正在尝试创建一个包含简单功能的模块,该模块用于创建具有已应用于其的某些通用格式的图。 Some of these functions would be applied to matplotlib objects that already exist and return other matplotlib objects to the main program. 其中一些功能将应用于已经存在的matplotlib对象,并将其他matplotlib对象返回给主程序。

This first segment of code is an example of how I currently generate plots and it works as is. 代码的第一部分是我当前如何生成图的示例,它按原样工作。

# 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)

I want to create a function that combines the add_axes() command with the grid() and set_xlabel() commands. 我想创建一个将add_axes()命令与grid()和set_xlabel()命令结合在一起的函数。 As a first attempt, ignoring all styling, I came up with the following function in my NTPlotTools.py module. 第一次尝试时,我忽略了所有样式,在NTPlotTools.py模块中提出了以下功能。

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

The script that calls the functions looks like: 调用函数的脚本如下所示:

# 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)

However, I get the following error message when I run the main code: 但是,运行主代码时出现以下错误消息:

---------------------------------------------------------------------------
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'

This says to me that the axesHandle is not a matplotlib axes object, and by extension, the CreateAxes() function call did not return a matplotlib axes object. 这对我来说,axesHandle不是matplotlib axes对象,并且通过扩展,CreateAxes()函数调用没有返回matplotlib axes对象。 Is there a trick to passing matplotlib objects to/from functions? 向/从函数传递matplotlib对象有技巧吗?

You are almost there. 你快到了 The problem is with this line. 问题在于这条线。

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

From the source code the add_axes method will looks like the following source codeadd_axes方法将如下所示

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

So when you invoke figureHandle.add_axes() without any parameter both args and kwrags will be empty. 因此,当您不带任何参数调用figureHandle.add_axes()argskwrags都将为空。 From the source code if args is empty add_axes method returns None . 如果args为空,则源代码中的add_axes方法从源代码返回None Hence this None value gets assigned to axesHandle and when you try to invoke axesHandle.grid(**gridStyle) you will get 因此,将这个None值分配给axesHandle ,当您尝试调用axesHandle.grid(**gridStyle)您将获得

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

Example

>>> 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)

So re-write the function by passing arguments to the add_axes method. 因此,通过将参数传递给add_axes方法来重新编写该函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM