Home > Back-end >  Plotly: Putting y-axis two plots in the same range in Python
Plotly: Putting y-axis two plots in the same range in Python

Time:12-25

I have two box plots side-by-side, but I want to have them to have the same y-axis range (150 - 400 in this case). Currently, the plot on the right side does not have the same y-axis range as the left one. I have tried it using fig.update_layout(yaxis_range=[140,410]), but I am not having any success here.

Here's the plot: 1

Here's the code:

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

df2 = pd.DataFrame()

np.random.seed(42)
df2['date'] = pd.date_range('2021-01-01', '2021-12-20', freq='D')
df2['month'] = df2['date'].dt.month
df2['spot_rate'] = np.random.randint(low=150, high=400, size=len(df2.index))

df4 = df2[df2['month'] == 12].tail(15)

fig = go.Figure()

fig = make_subplots(rows=1, cols=2, column_widths=[0.9, 0.1])

trendline = df2.groupby(['month']).spot_rate.median()
x1,y1 = list(trendline.index), trendline.values
stds = df2.groupby(['month']).spot_rate.std().values
n_vals = df2.groupby(['month']).date.count().values

## construct a 0.95 CI using mean ± z*std/sqrt(n)
y1_upper = list(y1   1.96*stds/np.sqrt(n_vals))
y1_lower = list(y1 - 1.96*stds/np.sqrt(n_vals))
y1_lower = y1_lower[::-1]

x1_rev = x1[::-1]

fig.add_trace(go.Scatter(x=x1, y=y1, line_shape="spline", line_color="blue", name="trendline"))

fig.add_trace(go.Scatter(
    x=x1 x1_rev,
    y=y1_upper y1_lower,
    line_shape="spline",
    fill='toself',
    fillcolor='rgba(255,192,203,0.5)',
    line_color='rgba(255,255,255,0)',
    showlegend=False,
    name="0.95 CI",
))

fig.add_trace(go.Box(y = df2['spot_rate'],
                     x = df2['month'],
                     marker_color = '#6AF954',
                     name = 'Monthly'),
             row=1, col=1)

fig.add_trace(go.Box(y = df4['spot_rate'], 
                     x = df4['month'],
                     marker_color = "orange",
                     name = "Past 15 days"),
             row=1, col=2)

fig.update_layout(paper_bgcolor="black",
                    plot_bgcolor="black",#template="plotly_dark",
                  font_color="white",
                  title="Spot Rates by Time",
                  xaxis_title="Month",
                  yaxis_title="Spot Rate",
                 yaxis_range=[140,410])

fig.show()

CodePudding user response:

You can pass the argument yaxis2 to the update_layout function:

fig.update_layout(yaxis2=dict(range=[140,410]))

enter image description here

  • Related