9

Do text and / or number input fields exist for matplotlib?

I have seen the widget Slider, but that is something different. I want a simple number input field.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • [This answer](https://stackoverflow.com/a/28009211/4124317) may be useful. Also [this question](https://stackoverflow.com/questions/43973758/how-do-i-make-matplotlib-open-a-box-for-user-comments) can help. – ImportanceOfBeingErnest Jun 23 '17 at 12:06

3 Answers3

13

You are looking for the TextBox interactive widget, which was added in 2.1:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(-2.0, 2.0, 0.001)
ydata = t ** 2
initial_text = "t ** 2"
l, = plt.plot(t, ydata, lw=2)


def submit(text):
    ydata = eval(text)
    l.set_ydata(ydata)
    ax.set_ylim(np.min(ydata), np.max(ydata))
    plt.draw()

axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'Evaluate', initial=initial_text)
text_box.on_submit(submit)

plt.show()
QuadmasterXLII
  • 432
  • 3
  • 11
  • 4
    If I understand [this](https://github.com/matplotlib/matplotlib/pull/6988) correctly, this will indeed be built in starting from version 2.1 (good job!). However, I strongly suggest removing `eval(text)` from that example, _especially_ since `text` is typed in by whoever's sitting in front of the computer. – Andras Deak -- Слава Україні Jun 09 '17 at 10:34
4

There currently exists no widgets that could be used to enter numbers as text. If you had a small selection of discrete numbers then you could use a RadioButton or you could use a slider as you've already suggested.

Your best would be to build a full GUI using Tkinter. This would allow you to add whatever GUI elements you need. It's also possible to embed matplotlib graphs in Tkinter, as shown in the two examples here and here.

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
  • 1
    I would recommend using QT, looks better ;) – tacaswell Aug 10 '14 at 21:41
  • Hah yeah OK I do admit QT looks better. [wxpython](http://stackoverflow.com/questions/10737459/embedding-a-matplotlib-figure-inside-a-wxpython-panel) is another alternative. – Ffisegydd Aug 11 '14 at 10:58
0

I like QuadmasterXLII's answer and have something to add. if using this with the update slider system you can use this to get the inner text.

# text box
t_box = plt.axes([0.05, 0.95, 0.8, 0.04])
file_text_box = TextBox(t_box, 'text', initial=init_txt)

def update(val)
    my_var = text_box.text_disp._text