plotly / plotly_express

Plotly Express - Simple syntax for complex charts. Now integrated into plotly.py!
https://plot.ly/python/plotly-express/
MIT License
4 stars 0 forks source link

Adding bar traces with add_trace gives different x-axis spacing than adding strip or box traces #177

Open meg256 opened 2 years ago

meg256 commented 2 years ago

Hi all. I am still new to plotly/px, so apologies if this is a simple fix.

I have a strip plot. I want to overlay a bar plot representing the mean of each group.

Problem: if I do this using add_trace, the bars and the strip plot dots do not line up.

I noticed that adding box plot traces seems to align just fine with my strip plot.

Example:

import pandas as pd
import plotly.express as px
df = pd.DataFrame.from_dict({'x': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2, 32: 2, 33: 2, 34: 2, 35: 2, 36: 2, 37: 2, 38: 2, 39: 2, 40: 2, 41: 2, 42: 2, 43: 2}, 'value': {0: 0.1, 1: 0.2, 2: 0.3, 3: 0.4, 4: 0.5, 5: 0.6, 6: 0.7, 7: 0.8, 8: 0.9, 9: 1.0, 10: 1.1, 11: 0.2, 12: 0.3, 13: 0.4, 14: 0.5, 15: 0.6, 16: 0.7, 17: 0.8, 18: 0.9, 19: 1.0, 20: 1.1, 21: 1.2, 22: 2.4, 23: 1.3, 24: 1.4, 25: 1.5, 26: 1.6, 27: 1.7, 28: 1.4, 29: 1.5, 30: 1.6, 31: 1.7, 32: 1.8, 33: 2.5, 34: 1.4, 35: 1.5, 36: 1.6, 37: 1.7, 38: 1.8, 39: 1.5, 40: 1.6, 41: 1.7, 42: 1.8, 43: 1.9}, 'group': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'A', 12: 'B', 13: 'C', 14: 'D', 15: 'E', 16: 'F', 17: 'G', 18: 'H', 19: 'I', 20: 'J', 21: 'K', 22: 'A', 23: 'B', 24: 'C', 25: 'D', 26: 'E', 27: 'F', 28: 'G', 29: 'H', 30: 'I', 31: 'J', 32: 'K', 33: 'A', 34: 'B', 35: 'C', 36: 'D', 37: 'E', 38: 'F', 39: 'G', 40: 'H', 41: 'I', 42: 'J', 43: 'K'}})
df_agg = df.groupby(by = ['x','group'], sort = False)['value'].agg('mean').reset_index()
fig = px.strip(df, x='x', y='value',color='group')
box_fig = px.box(df_agg,x='x',y='value',color='group')
bar_fig = px.bar(df_agg, x='x', y='value',color='group')

for box_data in box_fig.data:
    box_data['marker']['color'] = 'darkslategrey'
    box_data['showlegend'] = False
    fig.add_trace(box_data)     

for bar_data in bar_fig.data:
    bar_data['marker']['color'] = 'silver'
    bar_data['showlegend'] = False 
    fig.add_trace(bar_data)   

fig.show()

Output: troubleshoot

Can someone explain this or suggest a fix? Thanks!