[Python] How to set seaborn boxplot color and fill using two variables?

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using seaborn to plot a pandas dataframe. I'm currently able to set the color of the boxplot according to one variable ('G') but I also want to be able to set the fill of the boxplot according to another variable ('C'). This is a my code:

    fig, axes = plt.subplots(1, 2, figsize=(16, 6))
    colors = {"G1": '#7fb5b0', "G2": '#d86fad'}
    sns.set_style("ticks")
    sns.boxplot(x='Trial', y='level', hue='G', data=df1, palette=colors, ax=axes[0], dodge=True, showcaps=True)
    sns.boxplot(x='Trial', y='level', hue='G', data=df2, palette=colors, ax=axes[1], dodge=True, showcaps=True)


    So currently I have 4 boxes, two pink and two green, but I want to have one pink full box, one pink empty box, one green full box and one green empty box. Is there a way to achieve this?

    Edit: Here's some example data

    data1 = {'Trial': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
    'level': [20, 25, 23, 22, 7, 6, 5, 8, 46, 43, 40, 45, 11, 14, 10, 15],
    'G': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2', 'G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'],
    'C': ['C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2']}

    df1 = pd.DataFrame(data1)

    data2 = {'Trial': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2],
    'level': [22, 24, 23, 21, 3, 2, 4, 1, 30, 31, 29, 26, 7, 5, 9, 10],
    'G': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2', 'G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'],
    'C': ['C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2', 'C1', 'C1', 'C2', 'C2']}

    df2 = pd.DataFrame(data2)


    And this is the plot that I'm getting: [​IMG]

    Edit 2: I realize now that the issue here is not that I'm getting 4 boxes per trial (that was an issue I had before using a slightly modified code) but that I'm grouping the data only by 'G' and not by 'C'. So I would like to be able to separate my data by the combinations of 'G' and 'C' in a way that the variable 'G' determines the color and the variable 'C' determines the fill of the box

    Continue reading...

Compartilhe esta Página