Search code examples
pythonjupyter-notebookbqplot

Tighter layout of bqplot figures in Jupyter


I have created several plots in the Jupyter notebook using bqplot. The plots have been arranged using the Jupyter widget HBox and VBox layout attributes. However, I can't work out how to get a tight layout between the rows of subplots. What is the best method of getting a tighter layout?

Below is an example of Python code to run in the Jupyter notebook.

import numpy as np
from bqplot import *
from IPython.display import Javascript, display, clear_output
import ipywidgets as widgets

size = 100
scale = 100.
np.random.seed(0)
x_data = np.arange(size)
y_data = np.cumsum(np.random.randn(size)  * scale)

x_sc = LinearScale()
y_sc = LinearScale()

ax_x = Axis(label='X', scale=x_sc, grid_lines='solid')
ax_y = Axis(label='Y', scale=y_sc, orientation='vertical', grid_lines='solid')

line = Lines(x=x_data, y=x_data, scales={'x': x_sc, 'y': y_sc})

figy=[]
for i in range(2):
    figx=[]
    for j in range(3):
        figx.append(Figure(axes=[ax_x, ax_y], marks=[line], title='Example' + str(i*3+j), fig_margin = dict(top=30, bottom=10, left=20, right=20)))
    figy.append(widgets.HBox(figx)) 
display(widgets.VBox(figy, align_content = 'stretch'))

enter image description here


Solution

  • Here is a solution:

    import numpy as np
    from bqplot import *
    from IPython.display import Javascript, display, clear_output
    import ipywidgets as widgets
    
    size = 100
    scale = 100.
    np.random.seed(0)
    x_data = np.arange(size)
    y_data = np.cumsum(np.random.randn(size)  * scale)
    
    x_sc = LinearScale()
    y_sc = LinearScale()
    
    ax_x = Axis(label='X', scale=x_sc, grid_lines='solid')
    ax_y = Axis(label='Y', scale=y_sc, orientation='vertical', grid_lines='solid')
    
    line = Lines(x=x_data, y=x_data, scales={'x': x_sc, 'y': y_sc})
    
    fig_layout = widgets.Layout(width='auto', height='auto')
    
    figy=[]
    for i in range(2):
        figx=[]
        for j in range(3):
            figx.append(Figure(layout=fig_layout, axes=[ax_x, ax_y], marks=[line], title='Example' + str(i*3+j), fig_margin = dict(top=30, bottom=10, left=20, right=20)))
        figy.append(widgets.HBox(figx))
    display(widgets.VBox(figy, align_content = 'stretch'))
    

    basically overriding the layout attribute of the figure. bqplot figures have a fixed natural height.

    enter image description here