在python中使用matplotlib事件更改现有列表

2024-09-29 19:27:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个程序来识别功率密度谱中的重要频率。我已经自动找到了一个重要的峰值列表。但是现在我想用可视化的方式查看它们,并使用图canvas.mpl\u connect('key\u press\u event',ontype)http://matplotlib.org/users/event_handling.html

由于我想添加多个峰值,我想更新已用列表。虽然我得到了一个UnboundLocalError:local变量'frequencyLIST'在赋值之前被引用。你知道吗

def interactiveMethod(frequency,PDS, frequencyLIST,figureName):
#frequency and PDS is the input list of data, frequencyLIST is my found list of
#frequencies and figureName is the figure I previously made which I want to use the
#event on.

 def ontype(event):
  if event.key == 'a':
   #Getting the event xdata
   x = event.xdata      
   frequencyCut = frequency[np.where((frequency > x - 2) & (frequency < x + 2))]
   PDSCut = PDS[np.where((frequency > x - 2) & (frequency < x + 2))]

   #Find the maximum PDS, as this corresponds to a peak
   PDSMax = np.max(PDSCut)
   frequencyMax = frequencyCut[np.where(PDSCut == PDSMax)][0]

   #Updating the new list using the found frequency
   frequencyLIST = np.append(frequencyLIST,frequencyMax)

 figureName.canvas.mpl_connect('key_press_event',ontype)

我不知道我应该把这个频率列表放在哪里以便更新它。你知道吗

python版本:2.7.3 32位

matplotlib版本:1.3.0

numpy版本:1.7.1

ubuntu 13.1版

我还有一个完整的雨篷(不知道是哪个版本)


Tags: thekey版本event列表isnpwhere
1条回答
网友
1楼 · 发布于 2024-09-29 19:27:36

frequencyLIST变量传递给最外层的方法(interactiveMethod),而不是传递给内部方法(ontype)。快速修复方法是将以下行添加到内部方法:

def ontype(event):
    global frequencyLIST
    # ... following lines unaltered ...

您可以在this Stack Overflow question中阅读更多关于Python作用域变量的方法,以及与您类似的一个怪癖

相关问题 更多 >

    热门问题