python - 如何在 Seaborn boxplot 中编辑 mustache 、传单、帽等的属性

标签 python pandas matplotlib boxplot seaborn

我使用 Seaborn 包创建了一个嵌套箱线图和一个叠加的 strip 图。我在 stackoverflow 上看到了关于如何为 individual boxes 编辑 box 属性的答案和 all boxes使用 sns.boxplot 生成的 ax.artists。

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

默认情节: Default Plot

想要的情节: Desired Plot

这是我的引用代码:

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)

最佳答案

编辑:请注意,此方法似乎不再适用于 >=3.5 的 matplotlib 版本。参见 the answer by @JohanC获取最新答案

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

这是一个创建箱线图的脚本(基于示例 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()

enter image description here

关于python - 如何在 Seaborn boxplot 中编辑 mustache 、传单、帽等的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36874697/

相关文章:

python - `pip` 安装 `pylint` 时会安装哪些文件?

python - 在 Pandas 中添加缺失的行

python - 使用 python pandas .to_csv 附加到 csv 时如何强制换行

python - 如何避免 matplotlib.pyplot 中的线条颜色重复?

python - 如何在 Matplotlib 中反转轴并设置极坐标图的零位置?

python - 如何绘制预测值与真实值的关系图?

python - 如何在 Python 中将测量的发射线数据与高斯函数拟合? (原子光谱)

python - 在 Python 中安装 mahotas 后无法定位 freeimage

python - 在 groupby pandas 内有条件地设置值

python - 对数对数图中的寄生虫 x Axis