Search code examples
pythonfunctionmatplotlibscaling

What does "inverse" do in this ax.set_yscale argument and why is it user-defined?


I recently posted a question where I was asking how to do inverse log scaling on the y-axis for a plot I was making. The answer I accepted used this code-

def forward(x):
    return 2**x

def inverse(x):
    return np.log2(x)

ax.set_yscale('function', functions=(forward,inverse))

The idea being you modify the two functions to 1) define the equation to which to scale the axis and 2) inverse it. I changed some constants in the forward and inverse to make the scaling less pronounced in my actual application.

def forward(x):
    return 1.1**x

def inverse(x):
    return 0.01*(np.log2(x))

However, after fiddling with said constants, I noticed changing the "forward" function changes the scale of the plot, but changing the "inverse" function doesn't seem to change it in any way. Even after reading the documentation, I'm confused as to what the purpose of the inverse function is and why it's explicitly defined by the user. Wouldn't it make more sense for the module to calculate the inverse itself to eliminate the chance for error in the user-defined function?


Solution

  • Check out the Developer's guide for creating scales and transformations, it states about the forward and inverse transformations:

    [forward]: A transformation from data coordinates into display coordinates.

    [inverse]: An inverse of that transformation. This is used, for example, to convert mouse positions from screen space back into data space.

    As to

    Wouldn't it make more sense for the module to calculate the inverse itself

    I'd strongly say no. Finding inversions of functions can be tough (as in your case!), and you should be able to do it yourself if you're planning on making a custom scale in the first place.

    By the way: in your case, for example, I'd say that your def inverse() is wrong, as WolframAlpha finds that the inverse of 1.1**x is actually 10.4921*np.log(x), not 0.01*(np.log2(x)).