2016-08-22 14 views
1

このトピックはしばしば飛び出していますが、多くの試行、検索、やり取りの後、私はあなたにそれを戻しています。Python matplotlib blitとテキストの更新

私はmatplotlibの図を含むクラスを持っています。この図では、テキストが必要です。ユーザーがキーを押すと、軸の重いものをすべて描画することなく、テキストが何かに更新されます。私はここで誰かをblitする必要があるように見えますが、どうですか?ここに実例があります。私が今までに得た最高のものです。

import matplotlib as mpl 
mpl.use('TkAgg') 
import matplotlib.pyplot as plt 
import numpy as np 

class textUpdater: 
    def __init__(self): 
     self.fig, self.ax = plt.subplots() 
     # self.text = plt.figtext(.02, .14, 'Blibli') 
     self.text = self.ax.text(0, .5, 'Blabla')#, transform = self.ax.transAxes)#, animated=True) 

     self.fig.canvas.mpl_connect('key_press_event', self.action) 
     self.fig.canvas.draw() 

     plt.show() 

    def action(self, event): 
     if event.key == 'z': 
      self.text.set_text('Blooooo') 
      self.ax.draw_artist(self.text) 
      self.fig.canvas.blit(self.text.get_window_extent()) 

textUpdater() 

最初の質問:物をブリッとすると、前のテキストが後ろに表示されます。私はそれが消えたい!

2番目の:私は実際にどの軸からでもfigテキストとして持っていることを好みます。実現可能なように聞こえますか?

あなたは最高です、ありがとうございます。

答えて

2

これまでのテキストは、決して後ろにとどまりました。なぜなら、それを削除したことはないからです。これを防ぐには、図形を保存してからテキストを表示し、テキストが変更されたら保存された背景を復元してテキストを再表示する必要があります。

matplotlib.ArtistAnimationはすでにあなたのためのすべてのこれを行いますので、あなたはそれを使用することができます。

import matplotlib as mpl 
mpl.use('TkAgg') 
import matplotlib.pyplot as plt 
from matplotlib.animation import ArtistAnimation 
import numpy as np 

class textUpdater: 
    def __init__(self): 
     self.fig, self.ax = plt.subplots() 
     self.text = self.ax.text(.5, .5, 'Blabla') 

     self.fig.canvas.mpl_connect('key_press_event', self.action) 
     self.fig.canvas.draw() 

     self.animation = ArtistAnimation(self.fig, [(self.text,)]) 

     plt.show() 

    def action(self, event): 
     if event.key == 'z': 
      self.text.set_text('Blooooo') 

textUpdater() 

今、あなたの2番目の質問に、Figure.textだけの数字に属しているテキストを作成しますが、ArtistAnimationサポートしていません。どの軸にも属していないアーティストの場合は、この場合はArtistAnimationを再定義してこれをサポートする必要があります。

+0

ありがとうTim!何らかの理由で私はmpl.animationから離れなければならないと思っていましたが、完璧です。私はFigure.textのためにそれを適応させようとします。再度、感謝します。 – Etienne

+0

私は、この動作をサポートしていないことについて、[バグレポート](https://github.com/matplotlib/matplotlib/issues/6965)にmatplotlibを提出しました。私はすぐにパッチを提出すると思いますが、それまでは[ArtistAnimation._init_draw](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/animation.py#L1200)を再定義する必要があります)メソッドで 'artist.axes.figure'の代わりに' artist.get_figure() 'を使用しています。 –

関連する問題