【问题标题】:How to edit properties of whiskers, fliers, caps, etc. in Seaborn boxplot如何在 Seaborn 箱线图中编辑胡须、传单、帽子等的属性
【发布时间】:2016-08-20 20:36:03
【问题描述】:

我使用 Seaborn 包创建了一个带有重叠条形图的嵌套箱线图。我在 stackoverflow 上看到了有关如何使用 sns.boxplot 生成的 ax.artists 为 individual boxesall boxes 编辑 box 属性的答案。

有没有办法使用类似的方法来编辑胡须、帽子、传单等属性?目前,我必须手动编辑 seaborn -> categorical.py 文件中 _BoxPlotter() 类的 restyle_boxplot 方法中的值,以从默认绘图到所需绘图:

默认图:

想要的情节:

这是我的参考代码:

sns.set_style('whitegrid')

fig1, ax1 = plt.subplots()


ax1 = sns.boxplot(x="Facility", y="% Savings", hue="Analysis",
             data=totalSavings)

plt.setp(ax1.artists,fill=False) # <--- Current Artist functionality

ax1 = sns.stripplot(x="Facility", y="% Savings", hue="Analysis",
                    data=totalSavings, jitter=.05,edgecolor = 'gray',
                    split=True,linewidth = 0, size = 6,alpha = .6)

ax1.tick_params(axis='both', labelsize=13)
ax1.set_xticklabels(['Test 1','Test 2','Test 3','Test 4','Test 5'], rotation=90)
ax1.set_xlabel('')
ax1.set_ylabel('Percent Savings (%)', fontsize = 14)


handles, labels = ax1.get_legend_handles_labels()
legend1 = plt.legend(handles[0:3], ['A','B','C'],bbox_to_anchor=(1.05, 1), 
                     loc=2, borderaxespad=0.)
plt.setp(plt.gca().get_legend().get_texts(), fontsize='12') 
fig1.set_size_inches(10,7)

【问题讨论】:

    标签: python pandas matplotlib boxplot seaborn


    【解决方案1】:

    您需要编辑Line2D 对象,这些对象存储在ax.lines 中。

    这是一个创建箱线图的脚本(基于示例here),然后将线条和艺术家编辑为您问题中的样式(即没有填充,所有线条和标记的颜色相同,等等)

    您也可以修复图例中的矩形补丁,但您需要使用ax.get_legend().get_patches()

    我还在第二个轴上绘制了原始箱线图,作为参考。

    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()
    

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 2018-02-23
      • 2015-01-11
      相关资源
      最近更新 更多