Hey guys,
I’m trying to build a bar chart with a line secondary y chart but I’m facing problems to find a way to create a figure with the below design:
I did work on this and I’m a little close to finishing this, but I’m not understanding how to align the lines in the correct bar as you can see on the below chart:
The reproducible code is below, and any help on how to fix this will be very welcome:
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots
mockup_data={"revenue":[250, 130, 198, 125, 180, 130],
"profit":[35, 22, 28, 20, 25, 23],
"year":[2018, 2018, 2019, 2019, 2020, 2020],
"company":["you", "benchmark", "you",
"benchmark", "you", "benchmark", ]}
chart_data=pd.DataFrame.from_dict(mockup_data)
fig = make_subplots(specs=[[{"secondary_y": True}]])
bar_chart_fig = px.bar(chart_data,
x="year", y="revenue",
color_discrete_map={
"you": "#2C9F1B",
"benchmark": "#143DCB"},
color="company", barmode="group")
line_chart_fig=px.line(chart_data,
x="year", y="profit",
color="company",
color_discrete_map={
"you": "#D2EAFF",
"benchmark": "#CAF0E7"}
)
line_chart_fig.update_traces(line=dict(width=5), mode='lines+markers', marker=dict(size=15))
fig.add_trace(bar_chart_fig.data[0],
secondary_y=False,
)
fig.add_trace(line_chart_fig.data[0],
secondary_y=True
)
fig.add_trace(bar_chart_fig.data[1],
secondary_y=False,
)
fig.add_trace(line_chart_fig.data[1],
secondary_y=True
)
fig.update_layout(showlegend=False,
height=350, width=650,
margin=dict(l=15, r=15, b=8, t=8),
bargap=.4,bargroupgap=0.2
)
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#CED3E2',
tickfont=dict(color='#3E4453', size=12), zerolinecolor='#CED3E2')
fig.update_yaxes(showgrid=False, gridwidth=1, gridcolor='#CED3E2',
tickfont=dict(color='#3E4453', size=12), secondary_y=True)
fig.update_xaxes(showgrid=False, type='category')
Thank you very much in advance