[Python] How to adjust size of violin plot based on number of hues available for each category?

Discussão em 'Python' iniciado por Stack, Maio 7, 2025.

  1. Stack

    Stack Membro Participativo

    I need to create a violin plot based on two categories. But, some of the combination of categories are not available in the data. So it creates a white space, when i try to make the plot. I remember long ago i was able to adjust the size of the violins when the categories were not available in r using geom_violin(position= position_dodge(0.9)) refer to the attached image. Now i need to create a similar figure with python but when i try to make violin plot using seaborn i get whitespace when certain combinations of variables arent available (see image). Following is the code I am using in python. I would appreciate any help with this.

    Reproducible example

    import numpy as np

    # Define categories for Depth and Hydraulic Conductivity
    depth_categories = ["<0.64", "0.64-0.82", "0.82-0.90", ">0.9"]
    hydraulic_conductivity_categories = ["<0.2", "0.2-2.2", "2.2-15.5", ">15.5"]

    # Generate random HSI values
    np.random.seed(42) # For reproducibility
    hsi_values = np.random.uniform(low=0, high=35, size=30)

    # Generate random categories for Depth and Hydraulic Conductivity
    depth_values = np.random.choice(depth_categories, size=30)
    hydraulic_conductivity_values = np.random.choice(hydraulic_conductivity_categories, size=30)

    # Ensure not all combinations are available by removing some combinations
    for i in range(5):
    depth_values = depth_categories[i % len(depth_categories)]
    hydraulic_conductivity_values = hydraulic_conductivity_categories[(i + 1) % len(hydraulic_conductivity_categories)]

    # Create the DataFrame
    dummy_data = pd.DataFrame({
    'HSI': hsi_values,
    'Depth': depth_values,
    'Hydraulic_Conductivity': hydraulic_conductivity_values
    })
    # Violin plot for Soil Depth and Hydraulic Conductivity
    plt.figure(figsize=(12, 6))
    sns.violinplot(x='Depth', y='HSI', hue='Hydraulic_Conductivity', data=dummy_data, palette=color_palette,
    density_norm="count",
    cut = 0,
    gap = 0.1,
    linewidth=0.5,
    common_norm=False,
    dodge=True)
    plt.xlabel("DDDD")
    plt.ylabel("XXX")
    plt.title("Violin plot of XXX by YYYY and DDDD")
    plt.ylim(-5, 35)
    plt.legend(title='DDDD', loc='upper right')
    # sns.despine()# Remove the horizontal lines
    plt.show()


    [​IMG]

    Continue reading...

Compartilhe esta Página