How can I add two x-axis with only one y-axis in this bar chart?

Hi,

I would like to create a chart like the image below, but I can not find any keyword about this with Dash Plotly. Does it has some examples to achieve this goal by using plotly?

Thanks

I don’t think there’s anything pre-made but you can definitely create it with the different Plotly tools:

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


# Make random data
vals = np.random.rand(5) * 100
df = (
    pd.DataFrame(
        np.c_[vals, vals + (np.random.rand(5) - 0.5) * 20],
        columns=["Workforce", "Job postings"],
        index=["Category A", "Category B", "Category C", "Category D", "Category E"]
    )
    .rename_axis(index="category")
    .reset_index()
    .sort_values("Job postings")
)


# Create figure
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.15, shared_yaxes=True)

fig.add_bar(
    x=df["Workforce"],
    y=df["category"],
    orientation="h",
    row=1,
    col=2,
    hovertemplate="%{y}: %{x:.1f}%<extra></extra>",
    name="Workforce"
)

fig.add_bar(
    x=-df["Job postings"],
    y=df["category"],
    orientation="h",
    customdata=df["Job postings"],
    row=1,
    col=1,
    hovertemplate="%{y}: %{customdata:.1f}%<extra></extra>",
    name="Job postings",
)

fig.update_layout(
    margin=dict(b=20, t=20, l=20, r=20),
    width=800,
    height=450,
    yaxis_visible=False,
    yaxis_fixedrange=True,
    # xaxis
    xaxis_tick0=0,
    xaxis_dtick=20,
    xaxis_tickvals=[-100, -80, -60, -40, -20, 0],
    xaxis_ticktext=["100%", "80%", "60%", "40%", "20%", "0%"],
    xaxis_title="Job postings",
    xaxis_fixedrange=True,
    # xaxis2
    xaxis2_title="Workforce",
    showlegend=False,
    xaxis2_tickvals=[0, 20, 40, 60, 100],
    xaxis2_ticktext=["0%", "20%", "40%", "60%", "80%", "100%"],
    xaxis2_fixedrange=True,
    
)

for i, label in enumerate(df["category"]):
    fig.add_annotation(
        text=label,
        x=0.5, xanchor="center", xref="paper", ax=0,
        y=i, yref="y", ay=0,
        showarrow=False,
    )
    
fig.show()

1 Like

That’s a good idea. Thank you so much for your solution.