将参数传递给matplotlib中的子类格式\u坐标

2024-06-25 23:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我遵循了Benjamin Root的书“交互式应用程序使用Matplotlib”中的教程,对Matplotlib图像的format\u coord()方法进行了子类化。它起作用了。我有一个gui应用程序主.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参数。但是,我不知道怎么做。configfilename必须来自主.py但在这里,我只将名称'sp\u data\u pointer'作为add\u子图的参数。你知道吗

这让我很困惑,因为在我的代码中没有任何地方可以创建类的实例,而“init”方法可能是在我正在子类化的轴中处理的。有人能解释一下这些原则和/或一个肮脏的解决方法让我动起来吗(最好两者都解释!)你知道吗


Tags: 方法fromimportself应用程序data参数matplotlib
1条回答
网友
1楼 · 发布于 2024-06-25 23:20:47

我在这里只是猜测,但很可能是format_coord方法在初始化时实际上没有以任何方式使用。这将打开在创建之后设置configfilename的可能性。为此,可以将configfilename设置为类变量并为其定义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")

我不得不承认,仅仅为了设置格式而对Axes进行子类化有点奇怪。你知道吗

因此,另一种方法不是子类Axes,而是在主.py地址:

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

相关问题 更多 >