在jupyterlab中使用按钮控制matplotlib绘图,并实时更新绘图

发布时间 2023-04-28 16:39:09作者: 平平无奇小辣鸡

直接上代码

import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as widgets
import time
from IPython.display import Javascript, display, clear_output, update_display

class PltTest:

    def __init__(self):
        self.output = widgets.Output()

        self.tbtn1 = widgets.ToggleButton(value=False, description='Click 1', disabled=False,
                                     button_style='',  # 'success', 'info', 'warning', 'danger' or ''
                                     tooltip='Description',
                                     icon='check'  # (FontAwesome names without the `fa-` prefix)
                                     )

        self.tbtn2 = widgets.ToggleButton(value=False, description='Click 2', disabled=False,
                                     button_style='', tooltip='Description', icon='check')

        # An HBox lays out its children horizontally
        self.ui = widgets.HBox([self.tbtn1, self.tbtn2])
        self.fig, self.ax = None, None
        self.fig1, self.ax1 = None, None
        self.line = None
        self.line1 = None
        self.out1 = widgets.interactive_output(self.plot1, {'tb1': self.tbtn1})
        self.out2 = widgets.interactive_output(self.plot2, {'tb2': self.tbtn2})

    def plot1(self, tb1):
        print("tb1:", tb1)
        # if tb1['new']:
        if tb1:
            with self.output:
                self.fig, self.ax = plt.subplots(1, figsize=(5, 3.5))
                self.ax.set_title('figure1')
            # display(fig)
            plt.show()
        else:
            self.output.clear_output()
            # clear_output()
            plt.clf()
            plt.close()


    def plot2(self, tb2):
        print("tb2:", tb2)
        if tb2:
            with self.output:
                self.fig1, self.ax1 = plt.subplots(1, figsize=(5, 3.5))
                self.ax1.set_title('figure2')
            # display(fig1)
            plt.show()
        else:
            self.output.clear_output()
            # clear_output()
            plt.clf()
            plt.close()


    def draw1(self):
        # print("draw1")

        # plt.cla()
        if self.line is not None:
            self.line.remove()
            # line1.remove()
            # clear_output(wait=True)
        if self.fig and self.ax:
            x = np.cumsum(np.random.randn(150)) + 100.0
            self.line, = self.ax.plot(x, np.sin(x))
            self.line.set_ydata(np.cumsum(np.random.randn(150)) + 100.0)
            self.ax.relim()
            # 重设坐标轴,让图像更协调
            self.ax.autoscale_view()

            self.fig.canvas.draw()
            time.sleep(0.3)


    def draw2(self):
        # print("draw2")
        # plt.cla()
        if self.line1 is not None:
            self.line1.remove()
            # line1.remove()
            # clear_output(wait=True)
        if self.fig1 and self.ax1:
            x = np.cumsum(np.random.randn(150)) + 100.0
            self.line1, = self.ax1.plot(x, np.sin(x))
            self.line1.set_ydata(np.cumsum(np.random.randn(150)) + 100.0)
            self.ax1.relim()
            # 重设坐标轴,让图像更协调
            self.ax1.autoscale_view()

            self.fig1.canvas.draw()
            time.sleep(0.3)

    def dis(self):
        out1 = widgets.interactive_output(self.plot1, {'tb1': self.tbtn1})
        out2 = widgets.interactive_output(self.plot2, {'tb2': self.tbtn2})
        # tbtn1.observe(plot1, names='value')
        # tbtn2.observe(plot2, names='value')

        display(self.ui, out1, out2)

在jupyterlab中显示按钮点击可显示或关闭matplotlib绘图

# 交互式绘图需要安装  pip install ipympl
%matplotlib widget
from plt_test import PltTest

pt = PltTest()
pt.dis()

实时更新绘图内容

for i in range(10):
    pt.draw1()
    pt.draw2()