Search code examples
python-3.xjupyter-notebookplotlyplotly-python

Plotly Express Graphs side by side in Jupyter Notebook


I am having a challenge in displaying the Plotly.Express graphs side by side in Jupyter Notebook. It seems the feature is not yet available. Is there a way using ipywidgets, we can achieve this? Am trying to use below code where a, b are the graph objects to be shown side by side.

import ipywidgets
from ipywidgets import HBox, Layout, widgets
from IPython.display import display
out1=widgets.Output()
out2=widgets.Output()
with out1:
    display.display(a)
with out2:
    display.display(b)
hbox=widgets.HBox([out1,out2])
hbox

Solution

    • its straight forward to achieve with make_subplots()
    • demonstrated by creating traces with px and placing them in left / right
    • ipwidgets is second solution
    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    import plotly.express as px
    import pandas as pd
    import numpy as np
    import ipywidgets as widgets
    
    fig = make_subplots(rows=1, cols=2)
    fig_l = px.line(
        pd.DataFrame({"x": np.linspace(1, 100, 300), "y": np.sin(np.linspace(1, 20, 300))}),
        x="x",
        y="y",
    )
    fig_r = px.bar(
        pd.DataFrame({"x": np.linspace(1, 20, 30), "y": np.cos(np.linspace(1, 20, 30))}),
        x="x",
        y="y",
    )
    fig.add_trace(
        fig_l.data[0],
        row=1,
        col=1,
    )
    fig.add_trace(
        fig_r.data[0],
        row=1,
        col=2,
    )
    fig
    

    enter image description here

    ipwidgets

    widgets.HBox(
        [go.FigureWidget(fig_l.data, layout={"width":500, "height":300}), go.FigureWidget(fig_r.data, layout={"height":300})],
    )