I'm using a widgets.Output to display a matplotlib figure. I would like to be able to update the data shown in the figure/ axis by clicking a button, without generating a new figure.
Ultimately, the button function will retrieve data from a selected file - the graph does not need to update automatically like an animation.
In a previous version, I used:
import ipywidgets as wg
import matplotlib.pyplot as plt
output = wg.Output()
def make_plot(b):
with output:
f, ax = plt.subplots(figsize=figsize)
## details of plot here
output.on_displayed(make_plot)
but now get the message that wg.Output() has no attribute on_displayed.
I've tried the below, but it does not change the axis after clicking the button (the "confirm triggering function") does print correctly.
class GUI(object):
def __init__(self):
import ipywidgets as wg
import matplotlib.pyplot as plt
import numpy as np
self.display_button = wg.Button(description="Display graph")
self.graph_display = wg.Output()
## Shows empty axis but does not update with function when included here:
with self.graph_display:
self.fig, self.ax = plt.subplots()
def on_display_button_clicked(b):
print("confirm triggering function")
with self.graph_display:
## Does generate graph on button click when line below is uncommented, *but* appends a new graph each time
## self.fig, self.ax = plt.subplots()
self.ax.scatter(np.random.rand(10), np.random.rand(10))
self.display_button.on_click(on_display_button_clicked)
self.vbox = wg.VBox([self.display_button,
self.graph_display])
gui = GUI()
gui.vbox
I also tried modifying the example at https://stackoverflow.com/a/51060721, which works for displaying the specified graph when run once.
## modified from https://stackoverflow.com/a/51060721,
import matplotlib.pyplot as plt
import pandas as pd
import ipywidgets as widgets
import numpy as np
out1 = widgets.Output()
data1 = pd.DataFrame(np.random.normal(size = 50))
tab = widgets.Tab(children = [out1])
tab.set_title(0, 'First')
display(tab)
with out1:
fig1, axes1 = plt.subplots()
axes1.imshow('image.png')
data1.hist(ax = axes1)
plt.show(fig1)
However if I then run e.g. axes1.set_title("Graph title") in another jupyter cell, this does not modify the axes1 display.
axes1. In a Jupyter notebook environment, calling plt.show() within an output widget likeout1actually closes the figure within that specific output cell. Any subsequent modifications to the figure (like setting the title) after callingplt.show()won't ....