Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling figure height when using interactive plots in jupyter lab

I'm trying to use a combination of JupyterLab and the latest ipywidgets to have a basic graphic interface to explore some data. However, I cannot find a way to set up the figure height for the interactive plot

The notebook loads some file, then the user has the ability to pass some input using widgets (in the code below a text box). Finally, by pressing a button the graph is generated and passed to an Output widget.

This is the example code:


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)

The problem is that the graph automatically resizes no matter how large is the Output widget, and no matter of the figsize parameter passed. I would expect one of the two to control the output size particularly because there is no more the option to resize the graph manually.

As an additional info the HTML div dealing with the graph inside the Output widget is always 500px height no matter what I do

like image 216
Alessio Arena Avatar asked Jul 16 '19 07:07

Alessio Arena


Video Answer


1 Answers

Found the solution after a lot of research. Currently there is an open issue on github discussing just how %matplotlib widget behaves differently compared to the rest of matplotlib. Here is the link to the discussion

Basically this backend takes advantage of jupyter widgets and passes the figure to an Output widget. In my case I was nesting this into another Output widget to capture the plot. In this case neither the figsize attribute for the plot and the CSS layout attributes for the outer Output widget have an impact as the problem sits with this intermediate Output widget.

The good news is that the CSS layout attributes that we need to change are exposed. To modify them we can use:

fig.canvas.layout.width = '100%'
fig.canvas.layout.height = '900px'
like image 129
Alessio Arena Avatar answered Nov 14 '22 23:11

Alessio Arena