Grouped bar charts with corresponding line chart

Hi @bernl,

Here’s a work around that will hopefully get you started. The basic idea is to create a second xaxis (xaxis2) right on top of the categorical xaxis that you already have. The line traces can then be positioned on this second xaxis.

import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode
init_notebook_mode()

trace1 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)

data = [trace1, trace2]

bargap = 0.2
layout = go.Layout(
    barmode='group',
    bargap=bargap
)

# Create initial figure with grouped bar traces
fig = go.Figure(data=data, layout=layout)

# Add secondary x-axis that overlays categorical xaxis
fig.layout.xaxis2 = go.layout.XAxis(
    overlaying='x', range=[0, len(trace1.x)], showticklabels=False)

# Add a line traces, and associate with the second xaxis
for i in range(3):
    x = [i + bargap/2 + (1-bargap)/4, i + 1 - bargap/2 - (1-bargap)/4]
    y = [25 + 3*i, 22 + 4*i]
    scatt = fig.add_scatter(x=x, y=y, mode='lines', xaxis='x2',
                            showlegend=False, line={'color': 'gray'})

# plot in the jupyter notebook
iplot(fig)

Hope that helps!
-Jon

2 Likes