Home > Software engineering >  Python plot update on text input
Python plot update on text input

Time:05-26

I would like to create a plot with a function whose parameters can be updated by a text input on the figure in allocated textboxes. Let's say it would look something like the following: enter image description here

Here you input your values for a, b, c, and d and then press on the Update button to update the plot with those given parameters. Currently, I have the following, but I don't know how to connect the matplotlib.widgets.TextBox and an update button to the plot axes.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
from matplotlib.gridspec import GridSpec

def function(x, a, b, c, d):
     y = a*x**3   b*x**2   c*x   d
     return y

x = np.linspace(0, 10, 100)
y = function(x, 2, 2, 2, 2) # Initial values for a, b, c, and d

fig = plt.figure()
gs = GridSpec(6, 5, figure=fig)
ax1 = fig.add_subplot(gs[0:4, :])
ax2 = fig.add_subplot(gs[5, 0])
ax3 = fig.add_subplot(gs[5, 1])
ax4 = fig.add_subplot(gs[5, 2])
ax5 = fig.add_subplot(gs[5, 3])
ax6 = fig.add_subplot(gs[5, 4])

ax1.plot(x,y)

I'm not sure how to make the textboxes and the update button. I have been using https://matplotlib.org/stable/gallery/widgets/textbox.html as reference, but without prevail.

I appreciate any help. Thank you.

CodePudding user response:

I've made a very basic example, this doesn't rescale the axes to conform with the new function, but the functionality you want works.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox, Button
from matplotlib.gridspec import GridSpec

def function(x, a, b, c, d):
     y = a*x**3   b*x**2   c*x   d
     return y

x = np.linspace(0, 10, 100)
y = function(x, 2, 2, 2, 2) # Initial values for a, b, c, and d

#fig = plt.figure()
fig, ax = plt.subplots()
gs = GridSpec(6, 5, figure=fig)

axbox_text = fig.add_axes([0.1, 0.05, 0.5, 0.075])
text_box = TextBox(axbox_text, "Some title")

axbox_button = fig.add_axes([0.65, 0.05, 0.1, 0.075])
button = Button(axbox_button, "Hello")

def submit(expression):
    print(f"Pressed somewhere {expression}")
    if expression.inaxes == axbox_button: # Make sure the button was pressed
        print(f"Pressed button, value is {text_box.text}")
        ax.lines.clear()
        y = function(x, float(text_box.text), 2, 2, 2)
        ax.plot(x, y)
        

text_box.disconnect(text_box.disconnect_events) # Disconnect all other events
text_box.connect_event('button_press_event', submit) # Connect the button event

ax.plot(x,y)

plt.show()

CodePudding user response:

What you are trying to do goes beyond the scope of regular plotting. You are describing a graphical user interface (GUI) with text entry boxes and buttons. Perhaps you should consider GUI tools such as PyQt or TKinter which you can use for the reactive parts and to display the plot.

  • Related