Axes.secondary_xaxis
takes as an argument a tuple of functions that convert between the two axis systems. Is it possible to pass arguments along to these functions when I call secondary_xaxis
?
Here is my use case:
I have a function setup_plot
that sets the axes, legend, etc of a plot. The plot will be given a primary linear x axis and a secondary x axis that scales by (unique_param / x). That unique_param is different for each plot, so I would like to be able to call setup_plot(axis, unique_param)
, and pass that param on to the scaling function when it calls axis.secondary_xaxis()
.
I suggest using https://docs.python.org/3.8/library/functools.html#functools.partial to close over your parameter, so something like
def setup_plot(ax, unique_param):
def forward(T, param):
return T * param
def inv(d, param):
return d / param
ax.secondary_xaxis(
-0.2,
functions=(partial(forward, param=unique_param),
partial(inv, param=unique_param))
)
Thank you! This takes care of getting the unique parameter into the scaling function’s namespace. I didn’t know that one could define a function within a function in python. I tried this while omitting the partial
and it seemed to work fine; what is the reason for adding the partial()
?
Something like this would be a nice example for the Secondary Axis figure gallery. I think my situation might be a common one: adding an axis scale that depends on a tunable parameter of the experiment.
I was sleepy and did not think too hard about where I defined the conversion functions.
partial
is more-or-less doing the same thing as defining a function in the function (and creating a closure), but in a slightly terser way and doing a bit more book keeping (if you look at the repr for example the partial
one will be a bit nicer).