I am writing a Jupyter notebook that reads data from a sensor and I want to plot it as it is read. Data should start plotting when the user clicks a button. I tested the base code in the Spyder IDE and it works properly, but when I try to implement it on a Jupyter notebook it doesn't work properly.
Here's a MWE of my code. I kept the button, to show what I am trying to achieve.
import numpy as np
import ipywidgets as widgets
from ipywidgets import interactive
import matplotlib.pyplot as plt
from IPython.display import display
BotGraf = widgets.ToggleButton(value=False,
description='Graficar',
disabled=False,
button_style='info',
tooltip='Description',
icon='chart-line'
)
SalidaEjes = widgets.Output(layout=widgets.Layout(width="75%"))
def FBotGraf(ValBotGraf):
if ValBotGraf == True:
global NumEl
global d
NumEl = np.arange(0, 100)
d = np.zeros(100)
plt.ion()
with SalidaEjes:
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(NumEl, d, 'r-')
plt.show()
i=0
while i < 100:
d[i] = np.random.rand()
line1.set_ydata(d)
fig.canvas.draw()
fig.canvas.flush_events()
plt.show()
i += 1
IBotGraf = interactive(FBotGraf, ValBotGraf = BotGraf)
display(BotGraf)
display(SalidaEjes)
This way the plot shows up but plots the original data d = np.zeros(100)
and doesn't update the plot.
In the following cell however if I try to plot it:
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(NumEl, d, 'r-')
It shows that d
was in fact update in the cycle.
I read these questions: Interactive Graph with matplotlib and ipywidget and Interactive matplotlib using ipywidgets. But either didn't apply them properly or didn't solve the problem.
I guess it's not a complicated problem, but I can't figure it out.
Thanks for reading!