How to edit properties of whiskers, fliers, caps, etc. in Seaborn boxplot

后端 未结 1 1461
春和景丽
春和景丽 2020-12-09 20:49

I have created a nested boxplot with an overlayed stripplot using the Seaborn package. I have seen answers on stackoverflow regarding how to edit box

相关标签:
1条回答
  • 2020-12-09 21:15

    You need to edit the Line2D objects, which are stored in ax.lines.

    Heres a script to create a boxplot (based on the example here), and then edit the lines and artists to the style in your question (i.e. no fill, all the lines and markers the same colours, etc.)

    You can also fix the rectangle patches in the legend, but you need to use ax.get_legend().get_patches() for that.

    I've also plotted the original boxplot on a second Axes, as a reference.

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    fig,(ax1,ax2) = plt.subplots(2)
    
    sns.set_style("whitegrid")
    tips = sns.load_dataset("tips")
    
    sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax1)
    sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax2)
    
    for i,artist in enumerate(ax2.artists):
        # Set the linecolor on the artist to the facecolor, and set the facecolor to None
        col = artist.get_facecolor()
        artist.set_edgecolor(col)
        artist.set_facecolor('None')
    
        # Each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
        # Loop over them here, and use the same colour as above
        for j in range(i*6,i*6+6):
            line = ax2.lines[j]
            line.set_color(col)
            line.set_mfc(col)
            line.set_mec(col)
    
    # Also fix the legend
    for legpatch in ax2.get_legend().get_patches():
        col = legpatch.get_facecolor()
        legpatch.set_edgecolor(col)
        legpatch.set_facecolor('None')
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题