调用函数时参数发生了什么变化?

2024-09-28 17:26:25 发布

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

我正在研究如何在matplotlib中格式化轴刻度线

http://matplotlib.org/examples/pylab_examples/custom_ticker1.html

该链接显示以下代码段

def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x*1e-6)

我很难理解x,pos值在使用时发生了什么

^{pr2}$

这个概念叫什么?在


Tags: theorgposhttpmatplotlib链接defhtml
1条回答
网友
1楼 · 发布于 2024-09-28 17:26:25

在线:

formatter = FuncFormatter(millions)

您正在创建一个FuncFormatter类的实例,该实例是用millions函数初始化的。matplotlib接受这个类作为api的一部分来格式化tick。在这个例子中,formatter对象被传递给y轴的set_major_formatter方法,这样记号将用millions函数格式化。在

您可以在matplotlib源代码中看到这是如何工作的。该类的定义如下:

^{pr2}$

所以现在存储在formatter中的对象将有一个属性func,它指向millions函数。当matplotlib调用您传递给它的formatter对象时,它将把参数(即由记号表示的值)传递给millions函数,该函数由self.func指向

由于millions函数只根据x值而不是位置格式化记号,因此millions的定义只包含pos参数作为伪占位符。它必须这样做,以便在格式化记号时matplotlib调用self.func(x, pos)时不会出现错误。在

相关问题 更多 >