pythonmatplotlibplotlydata-visualization

How to plot figures side by side in plotly Dash?


The following link provides code to plot a chart in plotly side by side with html components. However, I'm looking for a similar functionality like plt.subplot of matplotlib. The following image, taken from official documentation of matplotlib is an example of the desired output.

enter image description here


Solution

  • Solution

    With inset plots in plotly you can set two plots side by side, specifying a domain argument in the Layout component, that is,

    import plotly.graph_objs as go
    
    go.Layout(xaxis = dict(domain = [0.0, 0.45]),
              xaxis2 = dict(domain = [0.55, 1.0]),
             )
    

    where you can adjust the position of the x-axis of the figure switching the values between 0 and 1. For a full example, see the section below.

    Example

    As example to plot a scatter plot with a bar graph side by side,

    # Set plotly in offline mode
    import plotly.graph_objs as go
    import pandas as pd
    offline.init_notebook_mode(connected=True)
    
    # Simple Scatter plot
    trace0 = go.Scatter(x = [10, 20, 30],
                        y = [40, 30, 20]
    )
    
    # Simple Bar chart
    trace1 = go.Bar(x=['cat_1', 'cat_2', 'cat_3', 'cat_4'],
                    y=[5, 27, 31, 48],
    
                    xaxis='x2',
                    yaxis='y2'
                   )
    
    # Data component 
    data = [trace0, trace1]
    
    # Layout component
    layout = go.Layout(xaxis = dict(domain = [0.0, 0.45]),
                       xaxis2 = dict(domain = [0.55, 1.0]),
                       yaxis2 = dict(overlaying='y',
                                     anchor = 'free',
                                     position = 0.55
                                    )
    
                      )
    
    # Figure component
    fig = go.Figure(data=data, layout=layout)
    
    offline.iplot(fig)
    

    outputs the following image. enter image description here