計算を続行できるようにmatplotlibプロットをデタッチする方法はありますか?
-
19-08-2019 - |
質問
Pythonインタープリターでのこれらの指示の後、プロットのあるウィンドウが表示されます。
from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code
残念ながら、プログラムがさらに計算を行っている間にshow()
によって作成された図を対話的に探索し続ける方法がわかりません。
まったく可能ですか?計算が長い場合があり、中間結果の調査中に続行すると役立つ場合があります。
解決
ブロックしないmatplotlib
の呼び出しを使用:
draw()
の使用:
from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print 'continue computation'
# at the end call show to ensure window won't close.
show()
インタラクティブモードの使用:
from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())
print 'continue computation'
# at the end call show to ensure window won't close.
show()
他のヒント
キーワード「block」を使用して、ブロック動作をオーバーライドします。
from matplotlib.pyplot import show, plot
plot(1)
show(block=False)
# your code
コードを続行します。
非ブロッキング方法での使用をサポートしている場合は、使用しているライブラリを常に確認することをお勧めします。
ただし、より一般的なソリューションが必要な場合、または他に方法がない場合は、 multprocessing
モジュールがPythonに含まれています。計算は続行されます:
from multiprocessing import Process
from matplotlib.pyplot import plot, show
def plot_graph(*args):
for data in args:
plot(data)
show()
p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()
print 'yay'
print 'computation continues...'
print 'that rocks.'
print 'Now lets wait for the graph be closed to continue...:'
p.join()
これは、新しいプロセスを起動するオーバーヘッドがあり、複雑なシナリオでデバッグするのが難しい場合があるため、他のソリューション(matplotlib
のノンブロッキングAPI呼び出し)
試用
from matplotlib.pyplot import *
plot([1,2,3])
show(block=False)
# other code
# [...]
# Put
show()
# at the very end of your script
# to make sure Python doesn't bail out
# before you finished examining.
show()
ドキュメントには次のように記載されています。
非インタラクティブモードでは、すべての図を表示し、図が閉じるまでブロックします。インタラクティブモードでは、非インタラクティブモードからインタラクティブモードに変更する前に数値を作成しない限り、効果はありません(推奨されません)。その場合、数字は表示されますがブロックされません。
単一の実験的なキーワード引数
block
をTrue
またはFalse
に設定して、上記のブロッキング動作をオーバーライドできます。
このドキュメントは、matplotlib
のドキュメント(タイトル:
重要:何かを明確にするため。コマンドは.py
スクリプト内にあり、スクリプトはたとえばpython script.py
コンソールから。
私のために働く簡単な方法は次のとおりです:
- ショー内でブロック= Falseを使用します: plt.show(block = False)
- .pyスクリプトの別の show()最後にを使用します。
例 script.py
ファイル:
plt.imshow(*something*)
plt.colorbar()
plt.xlabel("true ")
plt.ylabel("predicted ")
plt.title(" the matrix")
# Add block = False
plt.show(block = False)
################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################
# the next command is the last line of my script
plt.show()
私の場合、計算中にいくつかのウィンドウをポップアップ表示したかったのです。参考までに、これが方法です:
from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw()
print 'continuing computation'
show()
PS。非常に便利な matplotlibのOOインターフェイスのガイド 。
まあ、ノンブロッキングコマンドを理解するのに苦労しました...しかし、ついに<!> quot; Cookbook / Matplotlib / Animations-選択したプロット要素のアニメーション <!> quot;たとえば、Ubuntu 10.04上のPython 2.6.5では、スレッドで動作します(、グローバル変数またはマルチプロセスPipe
を介してスレッド間でデータを渡します)。
スクリプトは次の場所にあります。 Animating_selected_plot_elements-thread.py -参照用に以下に貼り付けます(コメントを少なく):
import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx
import time
import threading
ax = p.subplot(111)
canvas = ax.figure.canvas
# for profiling
tstart = time.time()
# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)
# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)
# just a plain global var to pass data (from main, to plot update thread)
global mypass
# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()
# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
# parallel with gobject.idle_add(update_line)
def threadMainTest():
global mypass
global runthread
global pipe1main
print "tt"
interncount = 1
while runthread:
mypass += 1
if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
interncount *= 1.03
pipe1main.send(interncount)
time.sleep(0.01)
return
# main plot / GUI update
def update_line(*args):
global mypass
global t0
global runthread
global pipe1upd
if not runthread:
return False
if pipe1upd.poll(): # check first if there is anything to receive
myinterncount = pipe1upd.recv()
update_line.cnt = mypass
# restore the clean slate background
canvas.restore_region(background)
# update the data
line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
canvas.blit(ax.bbox)
if update_line.cnt>=500:
# print the timing info and quit
print 'FPS:' , update_line.cnt/(time.time()-tstart)
runthread=0
t0.join(1)
print "exiting"
sys.exit(0)
return True
global runthread
update_line.cnt = 0
mypass = 0
runthread=1
gobject.idle_add(update_line)
global t0
t0 = threading.Thread(target=threadMainTest)
t0.start()
# start the graphics update thread
p.show()
print "out" # will never print - show() blocks indefinitely!
これが誰かを助けることを願って、
乾杯!
多くの場合、ハードドライブ上の.pngファイルとして画像を保存する方が便利です。その理由は次のとおりです。
利点:
- プロセスの任意の時点で、ファイルを開いて確認し、閉じることができます。これは、アプリケーションが長時間実行されている場合に特に便利です。 時間。
- 何もポップアップせず、ウィンドウを強制的に開くことはありません。これは、多くの図を扱う場合に特に便利です。
- 後で参照するために画像にアクセスでき、Figureウィンドウを閉じても失われません。
欠点:
- 私が考えることができる唯一のことは、あなたが行ってフォルダを見つけ、自分で画像を開かなければならないということです。
コンソールで作業している場合、つまりIPython
は、他の回答で指摘されているようにplt.show(block=False)
を使用できます。ただし、怠け者の場合は、次のように入力できます。
plt.show(0)
同じになります。
plt.pause(0.001)
をコードに追加して、forループ内で実際に動作させる必要がありました(そうしないと、最初と最後のプロットのみが表示されます):
import matplotlib.pyplot as plt
plt.scatter([0], [1])
plt.draw()
plt.show(block=False)
for i in range(10):
plt.scatter([i], [i+1])
plt.draw()
plt.pause(0.001)
また、エラーが発生した場合でも、プロットに残りのコードを実行して表示することを望んでいました(デバッグを行うためにプロットを使用することもあります)。この小さなハックをコーディングして、このwith
ステートメント内のプロットがそのように動作するようにしました。
これはおそらく少し非標準的であり、製品コードにはお勧めできません。おそらく多くの隠された<!> quot; gotchas <!> quot;があります。このコードで。
from contextlib import contextmanager
@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
'''
To continue excecuting code when plt.show() is called
and keep the plot on displaying before this contex manager exits
(even if an error caused the exit).
'''
import matplotlib.pyplot
show_original = matplotlib.pyplot.show
def show_replacement(*args, **kwargs):
kwargs['block'] = False
show_original(*args, **kwargs)
matplotlib.pyplot.show = show_replacement
pylab_exists = True
try:
import pylab
except ImportError:
pylab_exists = False
if pylab_exists:
pylab.show = show_replacement
try:
yield
except Exception, err:
if keep_show_open_on_exit and even_when_error:
print "*********************************************"
print "Error early edition while waiting for show():"
print "*********************************************"
import traceback
print traceback.format_exc()
show_original()
print "*********************************************"
raise
finally:
matplotlib.pyplot.show = show_original
if pylab_exists:
pylab.show = show_original
if keep_show_open_on_exit:
show_original()
# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
with keep_plots_open():
pl.figure('a')
pl.plot([1,2,3], [4,5,6])
pl.plot([3,2,1], [4,5,6])
pl.show()
pl.figure('b')
pl.plot([1,2,3], [4,5,6])
pl.show()
time.sleep(1)
print '...'
time.sleep(1)
print '...'
time.sleep(1)
print '...'
this_will_surely_cause_an_error
適切な<!> quot;を実装する場合(エラーが発生した場合でも)プロットを開いたままにし、新しいプロットの表示を許可する<!> quot ;、ユーザーがいない場合はスクリプトを適切に終了します干渉はそれを別の方法で伝えます(バッチ実行の目的で)。
タイムアウト質問のようなものを使用するかもしれません<!> quot;スクリプトの終わり! \ nプロット出力を一時停止する場合は(pを押します(5秒あります):<!> quot; https://stackoverflow.com/questions/26704840から/ corner-cases-for-my-wait-for-user-input-interruption-implementation 。
私のシステムではshow()はブロックしませんが、スクリプトがユーザーがグラフと対話するのを待って(そして 'pick_event'コールバックを使用してデータを収集する)続行したいのですが。
プロットウィンドウが閉じるまで実行をブロックするために、以下を使用しました。
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)
# set processing to continue when window closed
def onclose(event):
fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)
fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed
# continue with further processing, perhaps using result from callbacks
ただし、canvas.start_event_loop_default()は次の警告を生成しました。
C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
warnings.warn(str,DeprecationWarning)
スクリプトはまだ実行されましたが
plt.figure(1)
plt.imshow(your_first_image)
plt.figure(2)
plt.imshow(your_second_image)
plt.show(block=False) # That's important
raw_input("Press ENTER to exist") # Useful when you run your Python script from the terminal and you want to hold the running to see your figures until you press Enter
私の意見では、このスレッドの答えは、すべてのシステムやアニメーションのようなより複雑な状況では機能しないメソッドを提供します。堅牢な方法が見つかった次のスレッドで、MiKTeXの答えを見ることをお勧めします。 matplotlibアニメーションが終了するまで待つ方法
複数の図を開き、それらをすべて開いたままにしたい場合、このコードは私のために働いた:
show(block=False)
draw()
OPはmatplotlib
プロットのデタッチについて尋ねます。ほとんどの回答は、Pythonインタープリター内からのコマンド実行を前提としています。ここに示されているユースケースは、file.py
が実行され、プロットを表示したいがPythonスクリプトを完了してコマンドプロンプトに戻るターミナル(たとえばbash)でコードをテストするための私の好みです。
このスタンドアロンファイルは、multiprocessing
を使用して、os._exit(1)
でデータをプロットするための別のプロセスを起動します。メインスレッドは、subprocess
はmainを強制的に終了しますが、プロットウィンドウが閉じるまで__main__
子プロセスは生きたままで応答します。それは完全に別のプロセスです。
このアプローチは、応答するコマンドプロンプトが表示されるFigureウィンドウを使用したMatlab開発セッションに少し似ています。このアプローチを使用すると、Figureウィンドウプロセスとのすべての接続が失われますが、開発とデバッグには問題ありません。ウィンドウを閉じてテストを続けます。
ps ax|grep -v grep |grep file.py
は、Pythonのみのコード実行用に設計されており、おそらく<=>よりも適しています。 <=>はクロスプラットフォームであるため、WindowsまたはMacで調整をほとんどまたはまったく行わずに正常に機能するはずです。基盤となるオペレーティングシステムを確認する必要はありません。これは、Linux Ubuntu 18.04LTSでテストされました。
#!/usr/bin/python3
import time
import multiprocessing
import os
def plot_graph(data):
from matplotlib.pyplot import plot, draw, show
print("entered plot_graph()")
plot(data)
show() # this will block and remain a viable process as long as the figure window is open
print("exiting plot_graph() process")
if __name__ == "__main__":
print("starting __main__")
multiprocessing.Process(target=plot_graph, args=([1, 2, 3],)).start()
time.sleep(5)
print("exiting main")
os._exit(0) # this exits immediately with no cleanup or buffer flushing
<=>を実行するとFigureウィンドウが表示され、その後<=>が終了しますが、独立したプロセスであるため、<=> + <=> Figureウィンドウはズーム、パン、その他のボタンで応答します。
bashコマンドプロンプトでプロセスを確認するには、次のようにします。
<=>
plt.show(block=False)
を使用し、スクリプトの最後でplt.show()
を呼び出します。
これにより、スクリプトの終了時にウィンドウが閉じられなくなります。