JMJ JMJ - 29 days ago 12
Python Question

What happened to the parameters when the function was called?

I am looking at how to format axis tick marks in matplotlib

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

The link shows the following pieces of code

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


I am having trouble with understanding what happened to the x, pos values when it is used

formatter = FuncFormatter(millions)


What is that concept called?

Answer

In the line:

formatter = FuncFormatter(millions)

you are creating an instance of the FuncFormatter class, which is being initialised with the millions function. This is a class which matplotlib accepts as part of its api to format ticks. In the example, the formatter object is passed to the set_major_formatter method for the y axis so that ticks will be formatted with the millions function.

You can see how this works in the matplotlib source code. The class is defined as follows:

class FuncFormatter(Formatter):
    """
    User defined function for formatting

    The function should take in two inputs (tick value *x* and position *pos*)
    and return a string
    """
    def __init__(self, func):
        self.func = func

    def __call__(self, x, pos=None):
        'Return the format for tick val *x* at position *pos*'
        return self.func(x, pos)

So now the object stored in formatter will have an attribute func which points to the millions function. When matplotlib makes a call to the formatter object that you have passed it, it will pass the arguments (i.e. the values represented by the ticks) to the millions function which is pointed to by self.func

Since the millions function only formats the ticks based on the x value and not on the position, the definition of millions only includes the pos argument as a dummy placeholder. It must do this in order for there not to be an error when self.func(x, pos) is called by matplotlib when it formats the ticks.