Storing mouse click event coordinates in PyPlot window

I want to get access to the cursor positions within a PyPlot window and store all clicked values into arrays. I was able to print out the x,y values but I failed to store them into arrays.

The code first I used is:

function test(event)
    println("Click: $(event[:xdata]), $(event[:ydata])")
end

fig = PyPlot.figure()
PyPlot.plot(0:1:10, 0:1:10)
cid = fig[:canvas][:mpl_connect]("button_press_event", test)

Running this small code snippet the x,y coordinates were printed as expected. However when I try to store the values into arrays applying the following code:

x = Array{Float64,1}(undef,1); x = fill!(x,0)
y = Array{Float64,1}(undef,1); y = fill!(y,0)
function test(event)
    println("Click: $(event[:xdata]), $(event[:ydata])")
    x = push!(x,event[:xdata])
    y = push!(y,event[:xdata])
end

fig = PyPlot.figure()
PyPlot.plot(0:1:10, 0:1:10)
cid = fig[:canvas][:mpl_connect]("button_press_event", test)

I got the follwing error code:

julia> Click: 4.622983870967742, 4.563359234907353
Traceback (most recent call last):
  File "C:\Users\Carsten\.julia\conda\3\lib\site-packages\matplotlib\cbook\__init__.py", line 215, in process
    func(*args, **kwargs)
RuntimeError: Julia exception: UndefVarError(:x)

How can I store the clicked values for further use?
Many thanks in advanced

1 Like

It is the famous global scope issue although it seems to be created unnecessarily here.

To assign a global variable within a local scope you need to add the keyword global before the assignments. However, you do not need the assignments after the calls to push!. Therefore simply replacing

    x = push!(x,event[:xdata])
    y = push!(y,event[:xdata])

with

    push!(x,event[:xdata])
    push!(y,event[:xdata])

will make your code work as expected.

In other cases, you either need to use the global keyword or take the global variables as parameters to your functions.

3 Likes