Search code examples
pythonplotlyscatter-plotstacked

Stacked scatter plot


Is it possible to have the scatter plot below stacked by “sex” and grouped by day similar to the bar graph in the background?

import plotly.express as px
import plotly.graph_objects as go
df = px.data.tips()

# Scatter Plot
fig = px.strip(df, x='day', y='tip', color='sex').update_traces(jitter = 1)

# Female bars
fig.add_bar(name='Female',
            x=['Sun', 'Sat', 'Thur', 'Fri'], y=[5, 6, 7, 8], marker_color='rgba(0,0,255,0.2)'
           )
# Male bars
fig.add_bar(name='Male',
            x=['Sun', 'Sat', 'Thur', 'Fri'], y=[8, 2, 4, 6], marker_color='rgba(255,0,0,0.2)'
           )

# Make bars stacked
fig.update_layout(barmode='stack')

fig.show()

Stacked bar graph non-stacked scatter plot


Solution

  • stripmode='overlay' does the job.

    import plotly.express as px
    import plotly.graph_objects as go
    df = px.data.tips()
    
    # Scatter Plot
    fig = px.strip(df, x='day', y='tip', color='sex', stripmode='overlay').update_traces(jitter = 1)
    
    
    # Female bars
    fig.add_bar(name='Female',
                x=['Sun', 'Sat', 'Thur', 'Fri'], y=[5, 6, 7, 8], marker_color='rgba(0,0,255,0.2)'
               )
    
    # Male bars
    fig.add_bar(name='Male',
                x=['Sun', 'Sat', 'Thur', 'Fri'], y=[8, 2, 4, 6], marker_color='rgba(255,0,0,0.2)'
               )
    
    # Make bars stacked
    fig.update_layout(barmode='stack')
    
    fig.show()
    

    Gives

    Stacked scatter plot