Skip to content
Advertisement

How to change label position of a TextBox object?

The default position of the TextBox label is to the left of it, as shown in the image. I would like to place the label below the box. Is this possible?

Example code and image are taken from the Matplotlib docs. enter image description here

import numpy as np
import matplotlib.pyplot as plt
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)
    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")
text_box.on_submit(submit)
text_box.set_val("t ** 2")  # Trigger `submit` with the initial string.

plt.show()

Advertisement

Answer

You can do it by manually changing the position of the label (Text artist).

Add this to the end of your script:

label = text_box.ax.get_children()[1] # label is a child of the TextBox axis
label.set_position([0.5,-.1]) # [x,y] - change here to set the position
# centering the text
label.set_verticalalignment('top')
label.set_horizontalalignment('center')

Sample TextBox with label below the box

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement