Search code examples
pythonplotlyviolin-plot

python: multiple split violine plot overlayed


I have a set of samples to illustrate in violin plots. Here is an example by plotly.

enter image description here

I want something similar, but multiple "blue" distributions on the left-hand side of the violin. Very likely the area under the distribution is semi-transparent and overlayed.

Is there any suggestion to plot it? It needs not to be plotly.

Thanks.


Solution

  • You can add as many traces as you want using fig.add_trace. Following the same example from plotly:

    import plotly.graph_objects as go
    
    import pandas as pd
    
    df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
    
    fig = go.Figure()
    
    fig.add_trace(go.Violin(x=df['day'][ df['smoker'] == 'Yes' ],
                            y=df['total_bill'][ df['smoker'] == 'Yes' ],
                            legendgroup='Yes', scalegroup='Yes', name='Yes',
                            side='negative',
                            line_color='blue')
                 )
    fig.add_trace(go.Violin(x=df['day'][ df['smoker'] == 'No' ],
                            y=df['total_bill'][ df['smoker'] == 'No' ],
                            legendgroup='No', scalegroup='No', name='No',
                            side='negative',
                            line_color='green')
                 )
    fig.add_trace(go.Violin(x=df['day'][ df['smoker'] == 'No' ],
                            y=df['total_bill'][ df['smoker'] == 'No' ],
                            legendgroup='No', scalegroup='No', name='No',
                            side='positive',
                            line_color='orange')
                 )
    fig.update_traces(meanline_visible=True)
    fig.update_layout(violingap=0, violinmode='overlay')
    fig.show()
    

    Would add another trace to the left side:

    enter image description here