[Python] Violin plot - Concatenating two violins in one

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe for which I am plotting violin plot. The dataframe has two categories A and B. I want left side to represent category A while right side represent category B. I am able to plot it but what I also want is to keep the boxes, whiskers interquartile ranges etc. to be separate for each group. My plot has just one box in center (image 1). I want something like as is in image 2 (ref: https://python-graph-gallery.com/54-grouped-violinplot/).

    Setting split=False is creating two separately voilins.

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt

    # Sample data for df1 and df2
    df1 = pd.DataFrame({
    'category': ['A', 'A', 'B', 'B', 'B'],
    'Value': [10, 200, 300, 40, 50]
    })

    df2 = pd.DataFrame({
    'category': ['A', 'A', 'B', 'B', 'B'],
    'Value': [3, 4, 5, 4, 1]
    })

    # Add group labels to each dataframe
    df1['day'] = 'thurs'
    df2['day'] = 'thurs'

    # Combine the dataframes
    combined_df = pd.concat([df1, df2])
    # Plot violin chart
    plt.figure(figsize=(10, 6))
    sns.violinplot(x='day', y='Value', hue = 'category', data=combined_df, split=True)
    plt.title('Violin Plot of df1 and df2')
    plt.show()

    Continue reading...

Compartilhe esta Página