注意
前往結尾以下載完整的範例程式碼。
文字方塊#
文字方塊小工具讓使用者以互動方式提供文字輸入,包括公式。 在此範例中,圖表會使用 on_submit
方法進行更新。當使用者在文字方塊中按下 Enter 鍵或離開文字方塊時,此方法會觸發 submit 函式的執行。
注意:matplotlib.widgets.TextBox
小工具與下列靜態元素不同:註解 和 放置文字方塊。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import TextBox
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
t = np.arange(-2.0, 2.0, 0.001)
l, = ax.plot(t, np.zeros_like(t), lw=2)
def submit(expression):
"""
Update the plotted function to the new math *expression*.
*expression* is a string using "t" as its independent variable, e.g.
"t ** 3".
"""
ydata = eval(expression, {'np': np}, {'t': t})
l.set_ydata(ydata)
ax.relim()
ax.autoscale_view()
plt.draw()
axbox = fig.add_axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, "Evaluate", textalignment="center")
text_box.on_submit(submit)
text_box.set_val("t ** 2") # Trigger `submit` with the initial string.
plt.show()
