My Coding > Programming language > Python > Python graphics > Matplotlib > Matplotlib Widgets > How to pass arguments to function called by on_changed in Matplotlib Widgets

How to pass arguments to function called by on_changed in Matplotlib Widgets

The main idea of any Matplotlib Widgets, is to call method on_changed, when anything changed in the Widget, for example movement of Slider or switching Radiobuttons, or changing status of CheckButtons. But the format of defining of this function do not give straight forward way to send any parameters except default one. And the question, how to send required parameters.

This is a standard way of making this call is:


ax_x = plt.axes([0.20, 0.25, 0.55, 0.05])
s_x = Slider(ax_x, 'name', min_val, max_val, valinit=initial_val)

def slider_update(val):
    some_variable = s_x.val

s_x.on_changed(slider_update)

where val is the parameter by default taken from the Widget status.

To submit any parameters, it is necessary to make lambda function of this call.


ax_x = plt.axes([0.20, 0.25, 0.55, 0.05])
s_x = Slider(ax_x, 'name', min_val, max_val, valinit=initial_val)

def slider_update(val, extra_variable):
    some_variable = s_x.val
    # some extra work with  extra_variable

s_x.on_changed(lambda new_val: slider_update(new_val, my_variable))

In this code we call function slider_update with two parameters - new_val with is default parameter, and my_variable - extra variable with we need to pass to this function. In the function these two variables will be val and slider_update, respectively.

This method is applicable for any Matplotlib Widgets working on this principle responding vide on_changed method


Published: 2022-09-24 22:05:14
Updated: 2022-09-24 22:06:01

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.