HaakonFlaar
HaakonFlaar

Reputation: 397

Plotly: Add figures with multiple subplots to one single figure

I would like to create two figures, each containing multiple subplots with shared xaxes, and add these together to a single figure. Multiple figures in subplots suggests using dashboard, but I am not satisfied with that solution and I do not believe you can have shared xaxes in that case.

I would want to create figures with subplots such as this example:

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

# Sub figure 1
sub_fig1 = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.02) 
candlestick1 = go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])

sub_fig1.add_trace(candlestick1, row=1, col=1)
sub_fig1.add_trace({'x': df['Date'], 'y': df['AAPL.Volume'], 'type': 'bar', 'name': 'Volume'}, row=2, col=1)
sub_fig1.update_layout(xaxis_rangeslider_visible=False)

    
# Sub figure 2
sub_fig2 = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.02) 
candlestick2 = go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'],
                high=df['AAPL.High'],
                low=df['AAPL.Low'],
                close=df['AAPL.Close'])

sub_fig2.add_trace(candlestick2, row=1, col=1)
sub_fig2.add_trace({'x': df['Date'], 'y': df['AAPL.Volume'], 'type': 'bar', 'name': 'Volume'}, row=2, col=1)
sub_fig2.update_layout(xaxis_rangeslider_visible=False)

sub_fig1.show()
sub_fig2.show()

# Add both sub figures to one subplot
# ???

Ideally, I would want to add these subplots on columns next to each other on the same row. Is that possible?

I get the following plots after running the code above, but like I said I want the figures to be side by side on the same row. Code result

Upvotes: 2

Views: 4322

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31146

  • focus on the detail of the axis layouts and you can make one sub-plots chart
  • for this case only two settings need to be modified - see below
sub_fig3 = make_subplots(rows=2, cols=2, shared_xaxes=True, vertical_spacing=0.02)

sub_fig3 = sub_fig3.add_trace(sub_fig1.data[0], row=1, col=1)
sub_fig3 = sub_fig3.add_trace(sub_fig1.data[1], row=2, col=1)
sub_fig3 = sub_fig3.add_trace(sub_fig2.data[0], row=1,col=2)
sub_fig3 = sub_fig3.add_trace(sub_fig2.data[1], row=2,col=2)


sub_fig3 = sub_fig3.update_layout(
    xaxis_rangeslider_visible=False, 
    xaxis3={"anchor": "y3"},
    xaxis2_rangeslider_visible=False,
)
sub_fig3.show()

enter image description here

Upvotes: 1

Related Questions