【问题标题】:Controlling figure height when using interactive plots in jupyter lab在 jupyter lab 中使用交互式绘图时控制图形高度
【发布时间】:2019-11-24 21:49:28
【问题描述】:

我正在尝试结合使用 JupyterLab 和最新的 ipywidgets 来拥有一个基本的图形界面来探索一些数据。但是,我找不到为交互式绘图设置图形高度的方法

笔记本加载一些文件,然后用户可以使用小部件(在文本框下方的代码中)传递一些输入。最后,通过按下按钮生成图表并将其传递给输出小部件。

这是示例代码:


import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output, display
import ipywidgets as widgets

data = pd.read_csv('data.csv')

def show_results(input):
    if 'fig' in locals():
        del fig

    with out:
        clear_output(True)
        fig, ax = plt.subplots(1, 1)
        ax.axis('equal')
        data.loc[input.value].plot(cmap='inferno_r', column='probability', ax=ax, legend=True)
        plt.show()


input = widgets.Text(placeholder='input field', description='Input:')

showMe = widgets.Button(
    description='Show me the results',
    tooltip='Show me',
)
out = widgets.Output(layout = {
            'width': '100%',
            'height': '900px',
            'border': '1px solid black'
        })


showMe.on_click(show_results)

display(input)
display(showMe)
display(out)

问题在于,无论输出小部件有多大,以及传递的 figsize 参数如何,图形都会自动调整大小。 我希望这两者中的一个能够控制输出大小,特别是因为没有更多的选项来手动调整图形的大小。

作为附加信息,无论我做什么,在输出小部件内处理图形的 HTML div 始终是 500px 高度

【问题讨论】:

    标签: matplotlib jupyter-lab ipywidgets


    【解决方案1】:

    上述解决方案对我不起作用。既没有使用rcParams 全局设置绘图尺寸,我仍然设法使用fig = plt.figure(figsize=(12,12)) 设置函数内部的图形尺寸:

    from ipywidgets import interactive
    import matplotlib.pyplot as plt
    
    import numpy as np
    
    def f(r,g,b):
        fig = plt.figure(figsize=(15,15)) # <-- Here the figure dimension is controlled
        ax = fig.add_subplot()
        ax.imshow(np.array(np.dstack([compvis[r],compvis[g],compvis[b]]))/65536)
        plt.show()
    
    interactive_plot = interactive(f, r = (0,15),g = (0,15),b = (0,15))
    
    interactive_plot
    

    【讨论】:

      【解决方案2】:

      经过大量研究找到了解决方案。目前在 github 上有一个未解决的问题,讨论 %matplotlib widget 与 matplotlib 的其余部分相比如何表现不同。 Here is the link to the discussion

      基本上,此后端利用 jupyter 小部件并将图形传递给输出小部件。在我的情况下,我将它嵌套到另一个输出小部件中以捕获绘图。 在这种情况下,绘图的 figsize 属性和外部输出小部件的 CSS 布局属性都没有影响,因为问题出在这个中间输出小部件上。

      好消息是我们需要更改的 CSS 布局属性已经公开。要修改它们,我们可以使用:

      fig.canvas.layout.width = '100%'
      fig.canvas.layout.height = '900px'
      

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 2015-06-23
        • 1970-01-01
        • 2018-04-12
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        • 2016-11-16
        • 2019-03-06
        相关资源
        最近更新 更多