2012-11-02 56 views
2

我有這樣的代碼:的Python:如何「錨」的文字是始終可見並set_text方法Matplotlib

from pylab import * 
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText 
import numpy as np 
import matplotlib.pylab as plt 


fig = plt.figure() 
ax = fig.add_subplot(111) 

ann = AnchoredText('If you zoom in or out, i stay here\nbut can you update this text?', 
        prop=dict(size=8), frameon=True, 
        loc=2, 
       ) 
ann.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") 
ax.add_artist(ann) 

delta = 0.025 
x = np.arange(-3.0, 3.0, delta) 
y = np.arange(-2.0, 2.0, delta) 
X, Y = np.meshgrid(x, y) 
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) 
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) 
Z = (Z1 - Z2) * 10 

plt.contourf(X, Y, Z) 

plt.show() 

有沒有辦法來錨文本總是可見的,但也可以使用set_text方法就像在文本對象中更新包含文本? 這裏我使用了AnchoredText,它完美地錨定了,但是我找不到一個方法來改變它包含的文本。 在AnchoredText Matplotlib文檔我找不到這種方法可用。 如果不能用AnchoredText完成,可以用一個簡單的文本對象來完成嗎?

編輯

我接受了大衛Zwicker的解決方案,並在這裏了在需要它的任何一個工作示例:

from pylab import * 
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText 
import numpy as np 
import matplotlib.pylab as plt 
import random 


fig = plt.figure() 
ax = fig.add_subplot(111) 

ann = AnchoredText('If you zoom in or out, i stay here\nbut can you update this text?$4.1f$ km s$^{-1}$', 
        prop=dict(size=15), frameon=True, 
        loc=2, 
       ) 
ann.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") 
ax.add_artist(ann) 

delta = 0.025 
x = np.arange(-3.0, 3.0, delta) 
y = np.arange(-2.0, 2.0, delta) 
X, Y = np.meshgrid(x, y) 
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) 
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) 
Z = (Z1 - Z2) * 10 

plt.contourf(X, Y, Z) 

a = ["hhhhh", "qqqqq", "aaaaaaa","ttttt","yyyyy","oooooooo"] 

def setanntext(self): 
     ann.txt.set_text(random.choice(a)) 
     plt.draw() 

buttonax = plt.axes([0.7, 0.05, 0.1, 0.1]) 
button = Button(buttonax, 'set text',color='0.85', hovercolor='0.95') 
button.on_clicked(setanntext) 

plt.show() 

回答

4

您可以訪問屬性txt。您可以更新使用

ann.txt.set_text('new text') 
plt.draw() 

plt.draw()需要更新的情節和展示新文本的錨定的文本。