【问题标题】:Can I show a plot created in another file on JupyterLab?我可以显示在 JupyterLab 上的另一个文件中创建的图吗?
【发布时间】:2022-06-21 01:52:34
【问题描述】:

我希望有一个交互式地图,您可以在其中单击,一旦单击,将绘制 SkewT 和 Hodograph,显示该位置的信息。因此,我创建了一个类,我在其中使用metpy库添加了所有必要的信息,并且我能够成功地创建这些图表:

SkewT 和 Hodograph 绘制

当我尝试将我创建的用于生成这些图的类导入 jupyterlab 时,问题就出现了。由于实际制作这些图的代码非常繁琐,我宁愿 将代码保存在单独的文件中并导入我的SoundingGraphs 类,但它不起作用。这些图表永远不会被绘制在单元格内,而是在日志中显示为警告和信息,我不知道为什么:

出现在日志中的图表

尝试在我的文件中使用plt.show(),尝试返回plt,然后在笔记本的单元格中使用plt.show(),尝试使用%matplotlib widget%matplotlib notebook%matplotlib inline,尝试更改jupyterlab版本,这些都没有改变任何东西。

我找到了一个我不喜欢的解决方案,但它确实有效,而不是执行 plt.show(),而是在我的课堂上执行此操作:

buffer = BytesIO()
plt.savefig(buffer, format='png')
return buffer

我会在笔记本上做:

image = Image()
display(image)

def on_generate_button_clicked(b):
    buffer = SoundingGraphs(infos)
    buffer.seek(0)
    image.value=buffer.read()
    image.format='png'

generate_button.on_click(on_generate_button_clicked)

我不太喜欢这种方法,因为我想进一步为我的绘图添加交互性,例如在悬停时显示绘图的值等等,因此我不只是想显示图像。所以我想知道是否确实可以plt.show() 在单元格的另一个文件中创建的绘图。

使用:

Python 3.6.9
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab-widgets==1.1.0
ipykernel==5.5.6
ipyleaflet==0.14.0
ipympl==0.8.8
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.7.0
matplotlib==3.3.4

谢谢!

【问题讨论】:

    标签: python python-3.x matplotlib jupyter jupyter-lab


    【解决方案1】:

    是的,毕竟有可能!

    %matplotlib widget 需要在笔记本的开头使用,并且由于类方法将从另一个函数调用(在 button.on_click 事件上),因此可以在其上方使用 @out.capture() 装饰器,以便plt.show() 被显示。也可以将图形作为类属性,以便能够进行更多控制。

    如果有人想复制,这里有一些工作代码:

    笔记本

    %matplotlib widget
    from ipywidgets import Button, Output
    from myfile import MyClass
    
    out = Output()
    
    example_button = Button(
        description='Example',
        disabled=False,
        button_style='',
        tooltip='Click me'
    )
    
    @out.capture()
    def on_example_button_clicked(b):
        example_button.disabled = True
        myclass = MyClass()
        myclass.create_plot()
        out.clear_output(wait=True)
        display(myclass.fig.canvas)
        example_button.disabled = False
    
    example_button.on_click(on_example_button_clicked)
    
    display(example_button)
    display(out)
    

    myfile.py

    import matplotlib.pyplot as plt
    
    class MyClass():
        def __init__(self):
            plt.ioff()  # otherwise it'll also show inside logs
            plt.clf()
            self.fig = plt.figure()
    
        def create_plot(self):
            plt.plot([1, 2, 3, 4])
            plt.ylabel('some numbers')
    

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 2019-07-04
      • 2020-10-25
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多