The TextBox widget in Matplotlib allows you to add interactive text input fields to your plots.
This widget is useful for accepting user input, such as labels, thresholds, or search terms, and then using that input to modify the plot or display information dynamically.
In this tutorial, we’ll cover the basics of creating and using the TextBox widget in Matplotlib, with examples demonstrating different applications, including updating plot titles, filtering data, and changing plot parameters based on user input.
1. Basic Setup for the TextBox
The TextBox widget provides an editable text input field. When the text in the box is changed, it triggers a callback function, allowing you to respond to user input in real-time.
Basic Structure of TextBox
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox # Sample data for a simple plot x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and plot fig, ax = plt.subplots() line, = ax.plot(x, y, label="sin(x)") plt.xlabel("X-axis") plt.ylabel("Y-axis") # Adjust layout to make room for TextBox plt.subplots_adjust(bottom=0.25) # Create an axis for the TextBox axbox = plt.axes([0.25, 0.1, 0.5, 0.05]) # [left, bottom, width, height] # Create the TextBox text_box = TextBox(axbox, "Title", initial="sin(x)") # Callback function to update the title def submit(text): ax.set_title(text) fig.canvas.draw_idle() # Link the TextBox to the callback function text_box.on_submit(submit) plt.show()
In this example:
- TextBox(axbox, “Title”, initial=”sin(x)”) creates a TextBox labeled “Title” with an initial value of “sin(x)”.
- The submit function is called whenever the user submits text, updating the plot title.
2. Changing Plot Labels Based on TextBox Input
You can use the TextBox to dynamically change plot labels. Here’s an example where the TextBox lets users set the x-axis and y-axis labels.
# Create figure and plot fig, ax = plt.subplots() line, = ax.plot(x, y, label="sin(x)") plt.subplots_adjust(bottom=0.3) # Create TextBoxes for X and Y axis labels axbox_x = plt.axes([0.2, 0.15, 0.3, 0.05]) axbox_y = plt.axes([0.6, 0.15, 0.3, 0.05]) textbox_x = TextBox(axbox_x, "X-axis Label", initial="X-axis") textbox_y = TextBox(axbox_y, "Y-axis Label", initial="Y-axis") # Update functions for X and Y labels def update_xlabel(text): ax.set_xlabel(text) fig.canvas.draw_idle() def update_ylabel(text): ax.set_ylabel(text) fig.canvas.draw_idle() # Link TextBoxes to the callback functions textbox_x.on_submit(update_xlabel) textbox_y.on_submit(update_ylabel) plt.show()
In this example:
- textbox_x and textbox_y are used to set the labels of the x and y axes, respectively.
- The update_xlabel and update_ylabel functions update the labels based on the TextBox input.
3. Using TextBox to Change Plot Parameters
You can use the TextBox widget to allow users to set parameters, such as line color, line width, or marker style.
# Create figure and plot fig, ax = plt.subplots() line, = ax.plot(x, y, label="sin(x)", color="blue", linewidth=2) plt.subplots_adjust(bottom=0.3) # Create TextBoxes for color and linewidth axbox_color = plt.axes([0.2, 0.15, 0.3, 0.05]) axbox_width = plt.axes([0.6, 0.15, 0.3, 0.05]) textbox_color = TextBox(axbox_color, "Line Color", initial="blue") textbox_width = TextBox(axbox_width, "Line Width", initial="2") # Update functions for line color and width def update_color(text): line.set_color(text) fig.canvas.draw_idle() def update_width(text): try: line.set_linewidth(float(text)) fig.canvas.draw_idle() except ValueError: print("Invalid width input") # Link TextBoxes to the callback functions textbox_color.on_submit(update_color) textbox_width.on_submit(update_width) plt.show()
In this example:
- textbox_color allows the user to enter a color name for the line.
- textbox_width allows the user to set the line width, but includes error handling to check if the input is a valid number.
4. Filtering Data with TextBox Input
The TextBox can also be used to filter data based on user input. Here’s an example where the user specifies a minimum and maximum x-range to filter displayed data points.
# Sample data for a scatter plot x = np.linspace(0, 10, 100) y = np.sin(x) # Create figure and scatter plot fig, ax = plt.subplots() sc = ax.scatter(x, y) plt.subplots_adjust(bottom=0.3) # Create TextBoxes for min and max x-range axbox_min = plt.axes([0.2, 0.15, 0.3, 0.05]) axbox_max = plt.axes([0.6, 0.15, 0.3, 0.05]) textbox_min = TextBox(axbox_min, "Min X", initial="0") textbox_max = TextBox(axbox_max, "Max X", initial="10") # Update function to filter data based on x-range def update_range(_): try: x_min = float(textbox_min.text) x_max = float(textbox_max.text) mask = (x >= x_min) & (x <= x_max) # Filter condition sc.set_offsets(np.c_[x[mask], y[mask]]) # Update scatter plot fig.canvas.draw_idle() except ValueError: print("Invalid input for range") # Link TextBoxes to the update function textbox_min.on_submit(update_range) textbox_max.on_submit(update_range) plt.show()
In this example:
- textbox_min and textbox_max allow the user to enter the minimum and maximum x-range.
- The update_range function filters the displayed data points within the specified range.
5. Searching and Highlighting Data Points
The TextBox widget can be used for text search functionality. This example allows the user to enter an x-value, and the corresponding data point is highlighted if it exists.
# Sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create scatter plot fig, ax = plt.subplots() sc = ax.scatter(x, y, label="Data") highlight, = ax.plot([], [], 'ro', label="Highlighted Point") # Red dot for highlighting plt.legend() plt.subplots_adjust(bottom=0.25) # Create a TextBox for x-value search axbox_search = plt.axes([0.3, 0.1, 0.4, 0.05]) textbox_search = TextBox(axbox_search, "Search X") # Callback function to search and highlight the point def search_point(text): try: x_val = float(text) if x_val in x: idx = np.where(x == x_val)[0][0] highlight.set_data([x[idx]], [y[idx]]) # Update highlight position else: highlight.set_data([], []) # Clear highlight if x_val not found fig.canvas.draw_idle() except ValueError: print("Invalid input for search") # Link the TextBox to the search function textbox_search.on_submit(search_point) plt.show()
In this example:
- textbox_search allows the user to enter an x-value to search for.
- The search_point function checks if the entered x-value exists and highlights the corresponding point.
6. Using TextBox to Adjust Plot Function
The TextBox can be used to dynamically adjust the function plotted based on user input. Here’s an example where the user enters a mathematical expression, and the plot updates accordingly.
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox import math # Sample data for x x = np.linspace(0, 10, 100) # Create figure and initial plot fig, ax = plt.subplots() line, = ax.plot(x, np.sin(x), label="y = sin(x)") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.subplots_adjust(bottom=0.25) # Create a TextBox for function input axbox = plt.axes([0.25, 0.1, 0.5, 0.05]) textbox_func = TextBox(axbox, "Function", initial="sin(x)") # Callback function to update the plot based on function input def update_function(expression): try: y = eval(expression, {"x": x, "np": np, "math": math}) line.set_ydata(y) line.set_label(f"y = {expression}") ax.legend() fig.canvas.draw_idle() except Exception as e: print(f"Invalid function input: {e}") # Link TextBox to the update function textbox_func.on_submit(update_function) plt.show()
In this example:
- textbox_func allows the user to input a mathematical expression, such as sin(x), cos(x), or x**2.
- The update_function function evaluates the input expression and updates the plot based on the entered function.
Warning: eval() can execute arbitrary code, so it should be used with caution, especially in untrusted environments. In a secure setting, it can be useful for evaluating mathematical expressions as shown here.
Summary
In this tutorial, we covered several ways to use the Matplotlib TextBox widget to create interactive plots:
- Basic TextBox Setup to update plot titles.
- Changing Plot Labels based on TextBox input.
- Using TextBox to Adjust Plot Parameters such as line color and width.
- Filtering Data within a Range using TextBox for min and max range inputs.
- Searching and Highlighting Data Points by entering x-values.
- Dynamically Updating Plot Functions by inputting mathematical expressions.