How to add a line plot on top of a stacked bar plot in plotly express in python

Viewed 1795

I have the following dataframe:

import pandas as pd
foo = pd.DataFrame({'week': [1,2,3,4,5,6,7,8],
                   'n': [20,20,20,18,18,10,10,5]})
foo['var_1'] = foo['week'] * 10
foo['var_2'] = 100 - foo['var_1']
foo_m = foo.melt(id_vars=['week', 'n'])
foo_m['n_perc'] = foo_m['n'] / foo_m['n'].max() * 100
foo_m


week    n   variable    value   n_perc
0   1   20  var_1   10  100.0
1   2   20  var_1   20  100.0
2   3   20  var_1   30  100.0
3   4   18  var_1   40  90.0
4   5   18  var_1   50  90.0
5   6   10  var_1   60  50.0
6   7   10  var_1   70  50.0
7   8   5   var_1   80  25.0
8   1   20  var_2   90  100.0
9   2   20  var_2   80  100.0
10  3   20  var_2   70  100.0
11  4   18  var_2   60  90.0
12  5   18  var_2   50  90.0
13  6   10  var_2   40  50.0
14  7   10  var_2   30  50.0
15  8   5   var_2   20  25.0

I am using the following code to create the stacked bar plot:

import plotly.express as px
px.bar(foo_m, x='week', y='value', color='variable')

enter image description here

I would like to add on top of this stacked bar plot, this line plot:

px.line(foo_m[['week', 'n_perc']].drop_duplicates(), x='week', y='n_perc')

enter image description here

Any ideas how I could that with plotly in python ??

3 Answers

My solution is this:

fig = px.line(foo_m[['week', 'n_perc']].drop_duplicates(), x='week', y='n_perc')

fig.add_bar(x=foo_m['week'].unique(), y=foo_m.query('variable == "var_1"')['value'], alignmentgroup='week')
fig.add_bar(x=foo_m['week'].unique(), y=foo_m.query('variable == "var_2"')['value'], alignmentgroup='week')
fig.update_layout(barmode='stack')
fig.show()

enter image description here

You can do the following :

fig = px.line(foo_m[['week', 'n_perc']].drop_duplicates(), x='week', y='n_perc')

and then :

fig.add_bar(foo_m, x='week', y='value', color='variable')

I usually do it using Plotly.graph as follows :

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(x , y , mode="line"))
fig.add_trace(go.Bar(x , y )

fig.show()
Related