Python 将参数传递到matplotlib中的子类格式坐标
我遵循Benjamin Root的书“使用Matplotlib的交互式应用程序”中的教程,对Matplotlib图像的format_coord()方法进行子类化。它起作用了。我有一个gui应用程序,其中main.py导入数据指针,并使用它更改在图像上移动鼠标时显示的交互数字Python 将参数传递到matplotlib中的子类格式坐标,python,matplotlib,instance,subclass,interactive,Python,Matplotlib,Instance,Subclass,Interactive,我遵循Benjamin Root的书“使用Matplotlib的交互式应用程序”中的教程,对Matplotlib图像的format_coord()方法进行子类化。它起作用了。我有一个gui应用程序,其中main.py导入数据指针,并使用它更改在图像上移动鼠标时显示的交互数字 from gui_stuff.datapointer import DataPointerLeftCart 然后通过调用来使用: self.ax_lhs = self.f_lhs.add_subplot(111,proje
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必须来自main.py,但这里我只将名称“sp_data_pointer”作为add_子批的参数
这让我很困惑,因为在我的代码中没有任何地方可以创建类的实例,“init”方法可能是在我正在子类化的轴中处理的。有人能解释一下原理和/或一个肮脏的解决方法让我动起来吗(两者都好!)我在这里只是猜测,但很可能是
格式协调方法在初始化时没有以任何方式实际使用。这将允许在创建后设置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
,而是在main.py中使用格式_-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
谢谢,我用了第一种方法,效果很好!