1
votes

I have two bar plots, one is positive, other is negative. I want to overlay them with same x-axis in plotly. How can I do this? Here is a simple example of two bar plots:

import plotly.express as px
import pandas as pd
df1 = pd.DataFrame({'x1':[1,2,3], 'y1':[1,1,1], 'col':['A','A','B']})
df2 = pd.DataFrame({'x2':[1,2,3], 'y2':[-1,-1,-1], 'col':['A','A','B']})
fig1 = px.bar(df1, x="x1", y="y1", color="col")
fig2 = px.bar(df2, x="x2", y="y2", color="col")
1

1 Answers

1
votes

If you rename your columns so that they have the same name (like 'x1' and 'y1') you can concatenate the dataframes. Plotly stacks them automatically:

df1 = pd.DataFrame({'x1':[1,2,3], 'y1':[1,1,1], 'col':['A','A','B']})
df2 = pd.DataFrame({'x1':[1,2,3], 'y1':[-1,-1,-1], 'col':['A','A','B']})
df = pd.concat((df1, df2))
px.bar(df, x='x1', y='y1', color='col')