开发者

Python: numpy and matplotlib anomaly

This is the first time I am using matplotlib and numpy.

Here goes the problem:

If I goto python cli, the intended code works fine. Here is that code

>>> from numpy import *
>>> y = array([1,2])
>>> y = append(y, y[len(y) - 1]+1)
>>> y
array([1, 2, 3])

But if I use it with matplotlib in a script I get this error.

line 26, in onkeypress
y = append(y, y[len(y) - 1]+1)
UnboundLocalError: local variable 'y' referenced before assignment

Here is my script:

from matplotlib.pyplot import figure, s开发者_StackOverflowhow
from numpy import *
figzoom = figure()
axzoom = figzoom.add_subplot(111, xlim=(0,10), ylim=(0, 10),autoscale_on=True)
x = array([1, 2  ])
y = array([1, 10 ])
def onkeypress(event):
    if event.key == "up":
        y = append(y, y[len(y) - 1]+1)
        x = append(x, x[len(x) - 1]  )
        axzoom.plot(x,y)

I tried "append"ing to a different array,say y1, and then y = y1.copy(). But I still get the same error. I must be missing something trivial here???!!!


When you assign to a variable inside a function, python creates a new variable that has local scope, and this new variable also hides the global variable.

So, the x and y inside onkeypress are local to the function. Hence, from python's point of view, they are uninitialized, and hence the error.

As GWW points out - declaring x, y as global will solve the problem. Also, if you do not assign x, y any new value, but only use their previously existing value, those values will refer to the global x, y.


It may work if you change the variables to global

def onkeypress(event):
    global y, x
    ...


Unless you include global y in your onkeypress() function, the y you're assigning to is scoped locally to the function. You can't use y on the right side of the assignment statement in which you're defining the local variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜