1

I would like to call a function by pressing a matplotlib-button.

Right now, following approach works:

  1. Run script
  2. Press start-button in diagram window => cond=True
  3. execute function in console by typing: plot_data()

The code looks similar to this,

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np

#---Create BUTTON---
axButton1 = plt.axes([0.1,0.05,0.05,0.05]) #left,bottom, width, height
btn1 = Button(axButton1,"Start")

def start(event):
    global cond
    cond = True
    print(cond)
btn1.on_clicked(start)

#---Setting empty list---
t = np.array([0])
data = np.array([0])
cond = False

#---Plotting REAL TIME data---
def plot_data():
    global cond, t, data
    if (cond == True):
        #SOMETHING WILL BE EXECUTED

However, I would like to execute the function when pressing the start button and not write the command into the console again separately. I tried to call the function "plot_data()" from the function which acess the start-button,

def start(event):
    global cond
    cond = True
    print(cond)
    plot_data()
btn1.on_clicked(start)

This however does not work. Any idea what I could try?

1 Answer 1

0

Following can be your solution

import matplotlib.pylab as plt
from matplotlib.widgets import Button

fig, ax = plt.subplots()
x = [i for i in range(10)]
y = [i for i in range(10)]
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'PLOT')

(xm, ym), (xM, yM) = bnext.label.clipbox.get_points()


def on_button_clicked(event):
    global x,y
    ax.plot(x,y)
    print(event)


bnext.on_clicked(on_button_clicked)
plt.show()

Paste above code in main.py and run python main.py.

IF YOU ARE USING JUPYTER NOTEBOOK USE BELOW

%matplotlib inline

from matplotlib.pyplot import *
import ipywidgets

button = ipywidgets.Button(description="Plot")
out = ipywidgets.Output()
x = [i for i in range(10)]
y = [i for i in range(10)]

def on_button_clicked(b):
    with out:
        plot(x,y)
        show()

button.on_click(on_button_clicked)

display(button)
out
Sign up to request clarification or add additional context in comments.

2 Comments

Not exactly what I'm looking for. But thanks for the quick reply.
Can you please elaborate the problem you are facing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.