How to add a secondary Y axis to a Plotly Express bar plot?

Viewed 45

I would like to add a second Y axis to my bar plot bellow, that is the number of citizens in integer: enter image description here

this graph was made using plotly:

import plotly.express as px

fig = px.bar(df, x="country",y="pourcent_visit",color="city",barmode='group')
# fig.add_hline(y=10)

fig.show() 
1 Answers

To my knowledge, there's no direct way to do this. But you can easily build a Plotly Express figure, grab the traces (and data structures) from there and combine them in a figure that allows multiple axes using fig = make_subplots(specs=[[{"secondary_y": True}]]). With no provided data sample, I'll use the built-in dataset px.data.tips() that I'm guessing to a large part resembles the structure of your real world dataset judging by the way you've applied the arguments in px.bar(). Details in the comments, but please don't hesitate to let me know if something is unclear.

Plot:

enter image description here

Complete code:

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# sample data
df = px.data.tips()

# figure setup with multiple axes
fig = make_subplots(specs=[[{"secondary_y": True}]])

# build plotly express plot
fig2 = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group")

# add traces from plotly express figure to first figure
for t in fig2.select_traces():
    fig.add_trace(t, secondary_y = False)
    
# handle data for secondary axis
df2 = df.groupby('day').agg('sum')#.reset_index()
df2 = df2.reindex(index = df['day'].unique()).reset_index()

# 
fig.add_trace(go.Scatter(x = df2['day'], y = df2['size'], mode = 'lines'), secondary_y = True)

# fix layout
fig.update_layout(legend_title_text = 'smoker')

fig.show()
Related