How to add secondary xaxis in plotly using plotly.express?

Viewed 803

I found only examples with yaxis. After following it, I obtained an error:

Invalid key specified in an element of the 'specs' argument to make_subplots: 'secondary_x'
    Valid keys include: ['type', 'secondary_y', 'colspan', 'rowspan', 'l', 'r', 'b', 't']

My code is below:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

from plotly.subplots import make_subplots

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2=pd.DataFrame({'x':[1,2,3],'y':[7,8,9]})

fig = px.scatter(df1, x='A', y='B')
fig.add_scatter(x=df2['x'], y=df2['y'])

fig.update_traces(name='Points', showlegend = True)


# Fake figure due to axis
subfig = make_subplots(specs=[[{"secondary_x": True}]])
df2=pd.DataFrame({'C':[10,20,30],'D':[40,50,60]})
fig2 = px.scatter(df2, x='C', y='D')
fig2.update_traces(xaxis="x2")
subfig.add_traces(fig.data + fig2.data)

fig.show()

After advice

The code contains:

fig.update_layout(legend=dict(
    yanchor="top",
    y=0.99,
    xanchor="left",
    x=0.83,
    font=dict(
        family="Trebuchet",
        size=20,
        color="black"
     ),
        bgcolor="LightGray",
        bordercolor="Black",
        borderwidth=0
))

Is it possible to combine this and fig.layout = layout?

1 Answers

The make_subplots method in Plotly doesn't support a secondary x-axis. However, you can create the secondary x-axis on your own in the layout using the methods XAxis and YAxis that you can import using: from plotly.graph_objs.layout import YAxis,XAxis.

Then you set the fig.layout to be layout you have created, and when you want to use the secondary x-axis and the secondary y-axis, pass them as arguments to go.Scatter

In your case, I think it looks cleaner to create the secondary y-axis on your own along with the secondary x-axis, and this also eliminates the need to use the make_subplots method.

Update: you can add other parameters to layout to format your legend.

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.graph_objs.layout import YAxis,XAxis

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2=pd.DataFrame({'x':[1,2,3],'y':[7,8,9]})

## sample DataFrame with different x-axis and y-axis
df3=pd.DataFrame({'C':[10,20,30],'D':[40,50,60]})

## add a secondary xaxis and yaxis in the layout
layout = go.Layout(
    xaxis2 = XAxis( 
        overlaying='x',
        side='top',
    ),
    yaxis2=YAxis(
        overlaying='y',
        side='right',
    ),
    legend=dict(
        yanchor="top",
        y=0.99,
        xanchor="left",
        x=0.83,
        font=dict(
            family="Trebuchet",
            size=20,
            color="black"
         ),
            bgcolor="LightGray",
            bordercolor="Black",
            borderwidth=0
    )
)

fig = px.scatter(df1, x='A', y='B')
fig.add_scatter(x=df2['x'], y=df2['y'])
fig.update_traces(name='Points', showlegend = True)

## set the layout to be the figure layout
fig.layout = layout

## add the final trace specifying the secondary x-axis and secondary y-axis
fig.add_trace(go.Scatter(x=df3['C'], y=df3['D'], xaxis='x2', yaxis='y2'))

fig.show()

enter image description here

Related