将参数传递给 matplotlib 中的 sub_classed format_coord

pass param to sub_classed format_coord in matplotlib

我按照 Benjamin Root 的书 "Interactive applications using Matplotlib" 中的教程对 matplotlib 图像轴的 class 方法进行了子format_coord() 方法。有用。我有一个 gui 应用程序,其中 main.py 导入数据指针并使用它来更改将鼠标移到图像上时显示的交互式数字。

from gui_stuff.datapointer import DataPointerLeftCart

然后通过调用使用:

self.ax_lhs = self.f_lhs.add_subplot(111,projection = 'sp_data_pointer')

DataPointerLeftCart 的精简代码在单独的文件中定义如下:

import matplotlib.projections as mproj
import matplotlib.transforms as mtransforms
from matplotlib.axes import Axes
import matplotlib.pyplot as plt


#Our own modules
from operations.configurations import configParser

class DataPointerLeftCart(Axes):
    name = 'sp_data_pointer'
    def format_coord(self, y, z):
        configparams = configParser(ConfigFile=configfilename)        
        centreY = float(configparams['CENTRE_Y'])#units are pixels
        scale = float(configparams['SCALE'])#nm^-1 per pixel

    new_qy = (y-(centreY))*scale

    return "Qy: %f (nm^-1)" % (new_qy)

mproj.projection_registry.register(DataPointerLeftPol)

configParser() 是一个函数,它读取文本文件并为我的程序创建一个包含各种重要配置编号的字典。最初这没有参数,configParser 指定了文本文件的位置,但最近我修改了整个程序,以便您指定配置文件的本地副本。这要求我能够传递一个 configfilename 参数。但是,我对如何执行此操作感到困惑。配置文件名必须来自 main.py 但这里我只将名称 'sp_data_pointer' 作为 add_subplot.

的参数

这让我感到困惑,因为我没有在任何地方(在我的代码中可见)创建 class 的实例并且可能采用了“init”方法照顾我正在 subclassing 的内部 Axes。有人可以解释一下原理和/或一个肮脏的解决方法来让我感动(最好是两者!)

我只是在这里猜测,但很可能 format_coord 方法在 Axes 初始化时实际上没有以任何方式使用。这将开启在创建后设置 configfilename 的可能性。为此,可以使配置文件名成为一个 class 变量并为其定义一个 setter。

class DataPointerLeftCart(Axes):
    name = 'sp_data_pointer'
    configfilename = None

    def format_coord(self, y, z):
        configparams = configParser(ConfigFile=self.configfilename)        
        centreY = float(configparams['CENTRE_Y'])#units are pixels
        scale = float(configparams['SCALE'])#nm^-1 per pixel
        new_qy = (y-(centreY))*scale
        return "Qy: %f (nm^-1)" % (new_qy)

    def set_config_filename(self,fname):
        self.configfilename = fname

然后在创建后调用setter。

self.ax_lhs = self.f_lhs.add_subplot(111,projection = 'sp_data_pointer')
self.ax_lhs.set_config_filename("myconfigfile.config")

我不得不承认我对 subclassing Axes 只是为了设置格式感到有点奇怪。

所以替代方案可能不是 subclass Axes,而是使用 main.py:

中的 format_coord
from operations.configurations import configParser
configfilename = "myconfigfile.config"

def format_coord(y, z):
    configparams = configParser(ConfigFile=configfilename)        
    centreY = float(configparams['CENTRE_Y'])#units are pixels
    scale = float(configparams['SCALE'])#nm^-1 per pixel
    new_qy = (y-(centreY))*scale
    return "Qy: %f (nm^-1)" % (new_qy)

ax_lhs = f_lhs.add_subplot(111)
ax_lhs.format_coord = format_coord