Kyle Ho
Kyle Ho

Reputation: 11

how to use Plotly express draw a chart with two Yaxis, one on left, one on rihgt?

I found out that Plotly express is more efficient than plotly.go, here is my question: how to use Plotly express draw a chart with two Yaxis, one on left, one on rihgt?

I am trying to draw a chart of tickdata that with askprice and tha sma of spread ="ask price - bid price", cause spread and ask price is different in scale , so i want to draw a two yasix picture, i did but, the two yaxis label are both on left side how can i Separate the yaxis?

fig = px.line(df, x="datetime", y=\['sma_spread', "sma_plus", "sma_minus"\])  
fig2 = px.scatter(df,x=df\['datetime'\], y=\['a1', "b1"\])  
fig2.update_traces(yaxis ="y2")

show(fig.add_traces(fig2.data))

Upvotes: 1

Views: 1291

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31166

  • you have missed one final step. Configure the second yaxis update_layout(yaxis2={"overlaying":"y", "side":"right"})
  • have generated a data frame that is same structure that your code uses to demonstrate

full MWE

import pandas as pd
import numpy as np
import plotly.express as px

# simulate data
df = pd.concat(
    [
        pd.DataFrame(
            (
                np.random.uniform(4.5, 5, [3, 1])
                * (1 + np.random.normal(loc=0.001, scale=0.01, size=100)).cumprod()
            ).T,
            columns=["sma_spread", "sma_plus", "sma_minus"],
        ).assign(datetime=pd.date_range("1-jan-2022", periods=100)),
        pd.DataFrame(
            (
                np.random.uniform(15, 16, [2, 1])
                * (1 + np.random.normal(loc=0.001, scale=0.01, size=100)).cumprod()
            ).T,
            columns=["a1", "b1"],
        ),
    ],
    axis=1,
)

fig = px.line(df, x="datetime", y=['sma_spread', "sma_plus", "sma_minus"])  
fig2 = px.scatter(df,x=df['datetime'], y=['a1', "b1"])  
fig2.update_traces(yaxis ="y2")
# one more step, config second axis
fig.add_traces(fig2.data).update_layout(yaxis2={"overlaying":"y", "side":"right"})

enter image description here

Upvotes: 2

Related Questions