@njohnson
-
To get a bar plot that contains both stacked and unstacked bars, you should use the
base
, the offset
and the bar width
. In this case donβt set barmode
in layout!!!
-
You can associate a second xaxis
only if you are referencing a trace to it,
but since you are referencing the bars to the bottom xaxis,
you must put the upper ticklabels as annotations.
import plotly.graph_objects as go
unstacked = go.Bar(
y= [37, 25, 21, 17, 14],
base = 0, #all bars in this trace have base at y=0
width = 0.45,# the width must be less than 1, and such that two adjacent bars have width sum <=1
offset = 0, #The first bar starts at x=0, the second at 1, etc
textposition='auto',
texttemplate= '%{y}')
stackedbottom = go.Bar(
y=[24,10, 9, 11],
base=0,
width = 0.45,
offset = 0.45, #the first bar starts at 0.45, the second at 1.45, etc
textposition='auto',
texttemplate= '%{y}'
)
stackedtop = go.Bar(
y=[13, 15, 12, 0, 8],
width = 0.45,
offset = 0.45,
base=[24, 10, 9, 0, 0],#24, 10, 9 are the previous three y vals to ensure stacking, and 0, 0 to put bars on base
textposition='auto',
texttemplate= '%{y}')
fig= go.Figure([unstacked, stackedbottom, stackedtop])
fig.update_layout(xaxis_tickvals=[0.45, 1.45, 2.45, 3.45, 4.45],
xaxis_ticktext=['A', 'B', 'C', 'D', 'E'],
xaxis_range=[-0.2, 5])
fig.show()
fig2=go.Figure([go.Bar(y=[8, 9, 10], base=0, width=0.8, offset=0),
go.Bar(y=[3, 4, 0], base=[8,9,10], width=0.8, offset=0)])
fig2.update_layout(xaxis_range=[-0.2, 3], xaxis_tickvals=[0.4, 1.4, 2.4],
xaxis_ticktext=[101, 102, 103],
annotations=[dict(x=X, y=Y, text=t, xref='x', yref='paper',
showarrow=False) for X, Y, t in zip([0.4, 1.4, 2.4], [1.07]*3, [201, 202, 203])])
fig2.show()