2

ユーザーがmatplotlibのイベント処理を介してグラフを操作できるようにするスクリプトを作成しようとしていますが、ターミナルから追加情報を入力する必要があります

呼び出すraw_input()とスクリプトが壊れているようで、RuntimeError: can't re-enter readlineエラーがスローされます

これを示す簡単なコードを次に示します。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def keypress(event):
    print 'You press the "%s" key' %event.key
    print 'is this true? Type yes or no'
    y_or_n = raw_input()

cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()

これは、python を使用して実行すると正常に動作しますが、ipython --pylab を使用すると中断します。残念ながら、インタラクティブモードが必要です

他の人がこの問題を抱えているのを見ましたが、解決策を見たことはありません

4

1 に答える 1

3

matplotlib がまだキープレスをリッスンしているため、問題が発生しています。残念ながら、イベントのリッスンを切断するだけでは、インタラクティブに機能しませんでした。ただし、このソリューションは機能しました。ただし、「y」、「e」、「s」、「n」、または「o」キーを使用できないという制限があります。必要に応じて、これに対する回避策があります。

import matplotlib.pyplot as plt
import numpy as np

#disable matplotlib keymaps
keyMaps = [key for key in plt.rcParams.keys() if 'keymap.' in key]
for keyMap in keyMaps:
    plt.rcParams[keyMap] = ''

str = ''

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def keypress(event):
    global str

    if event.key in ['y','e','s','n','o']:
        str += event.key
    else:   
        print 'You press the "%s" key' %event.key
        print 'is this true? Type yes or no'

    if str == 'yes':
        print str
        str = ''
    elif str == 'no':
        print str
        str = ''

cid = fig.canvas.mpl_connect('key_press_event', keypress)
plt.show()
于 2012-10-10T13:12:36.327 に答える