如何将LiveGraph嵌入ipywidgets的Output或Box容器组件中
问题描述
我参照两篇Stack Overflow回答实现了LiveGraph动态图表和线程变量更新功能,最终生成了每秒自动更新、幅值由滑块控制的动态图表,完整初始代码如下:
%matplotlib notebook from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation from threading import Thread, Lock import time import ipywidgets as widgets from IPython.display import display import numpy as np '''#################### Live Graph ####################''' # Create a new class which is a live graph class LiveGraph(object): def __init__(self, baseline): self.x_data, self.y_data = [], [] self.figure = plt.figure() self.line, = plt.plot(self.x_data, self.y_data) self.animation = FuncAnimation(self.figure, self.update, interval=1200) # define variable to be updated as a list self.baseline = [baseline] self.lock = Lock() self.th = Thread(target=self.thread_f, args = (self.baseline,), daemon=True) # start thread self.th.start() def update_baseline(self,baseline): # updating a list updates the thread argument with self.lock: self.baseline[0] = baseline # Updates animation def update(self, frame): self.line.set_data(self.x_data, self.y_data) self.figure.gca().relim() self.figure.gca().autoscale_view() return self.line, def show(self): plt.show() # Function called by thread that updates variables def thread_f(self, base): x = 0 while True: self.x_data.append(x) x += 1 self.y_data.append(base[0]) time.sleep(1) '''#################### Slider ####################''' # Function that updates baseline to slider value def update_baseline(v): global g new_value = v['new'] g.update_baseline(new_value) slider = widgets.IntSlider( value=10, min=0, max=200, step=1, description='value:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) slider.observe(update_baseline, names = 'value') '''#################### Display ####################''' display(slider) g = LiveGraph(slider.value)
后续我希望将该图表放入包含其他组件的更大界面中,尝试将LiveGraph放入Output组件,替换展示部分的代码为以下内容后没有任何图表展示:
out = widgets.Output(layout={'border': '1px solid black'}) with out: g = LiveGraph(slider.value) vbox = widgets.VBox([slider,out], align_self='stretch',justify_content='center') vbox
我需要将这个LiveGraph嵌入到Output组件或者Box容器组件中的实现方法。
解决方案
图表不显示的核心原因是在Output组件的上下文管理器中创建matplotlib图表后,没有主动触发图表渲染,仅需要修改两处代码即可实现嵌入效果:
- 在
with out代码块中实例化LiveGraph后,调用实例的show()方法触发渲染 - 显式调用display方法渲染整个容器组件
修改后的展示部分代码如下:
out = widgets.Output(layout={'border': '1px solid black'}) with out: g = LiveGraph(slider.value) g.show() # 新增这行触发图表渲染 vbox = widgets.VBox([slider,out], align_self='stretch',justify_content='center') display(vbox) # 显式渲染整个容器
如果以上方案仍有显示异常,可以将开头的%matplotlib notebook替换为%matplotlib widget,使用matplotlib的ipywidgets专属后端兼容性更好。
内容的提问来源于stack exchange,提问作者Marcelo Z
相关产品推荐
相关产品推荐

