Home > Blockchain >  Setting additional arguments during lambda function definition in a loop - same result when function
Setting additional arguments during lambda function definition in a loop - same result when function

Time:11-08

I want to create figure callbacks in a loop, with different additional input arguments to the callback for each figure. In the below code snippet the function prints "B" regardless of which figure I click in.

import matplotlib.pyplot as plt
import numpy as np

def onclick(event, key):
    print(key)

for k in ["A", "B"]:
    x = np.arange(1,10)
    y = x**2
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(k)
    ax.plot(x,y)
    cid = fig.canvas.mpl_connect('button_press_event', lambda tmp: onclick(tmp, k))

CodePudding user response:

Replace

lambda tmp: onclick(tmp, k)

with

functools.partial(onclick, key=k)

Full example:

from functools import partial
import numpy as np
import matplotlib.pyplot as plt

def onclick(event, key):
    print(key)

for k in ["A", "B"]:
    x = np.arange(1,10)
    y = x**2
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(k)
    ax.plot(x,y)
    cid = fig.canvas.mpl_connect('button_press_event', partial(onclick, key=k))

plt.show()
  • Related