python - 如何在seaborn boxplot中的相同子组之间创建间距?

标签 python seaborn boxplot

我目前有一个 seaborn 箱线图,如下所示:
Current box plot

x 轴上的每个分组(“色调”)都相互接触。

这个箱线图的代码是这样的:

bp_all = sns.boxplot(x='X_Values', y='Y_values', hue='Groups123', data=mydataframe, width=0.8, showfliers=False, linewidth=4.5, palette='coolwarm')

有什么方法可以在 3 个组之间创建一个小空间,使它们不会相互接触?

最佳答案

我找到了另一个用户发布的解决方案。此功能用于根据您选择的因素调整您创建的图形中所有对象的宽度

from matplotlib.patches import PathPatch

def adjust_box_widths(g, fac):
    """
    Adjust the withs of a seaborn-generated boxplot.
    """

    # iterating through Axes instances
    for ax in g.axes:

        # iterating through axes artists:
        for c in ax.get_children():

            # searching for PathPatches
            if isinstance(c, PathPatch):
                # getting current width of box:
                p = c.get_path()
                verts = p.vertices
                verts_sub = verts[:-1]
                xmin = np.min(verts_sub[:, 0])
                xmax = np.max(verts_sub[:, 0])
                xmid = 0.5*(xmin+xmax)
                xhalf = 0.5*(xmax - xmin)

                # setting new width of box
                xmin_new = xmid-fac*xhalf
                xmax_new = xmid+fac*xhalf
                verts_sub[verts_sub[:, 0] == xmin, 0] = xmin_new
                verts_sub[verts_sub[:, 0] == xmax, 0] = xmax_new

                # setting new width of median line
                for l in ax.lines:
                    if np.all(l.get_xdata() == [xmin, xmax]):
                        l.set_xdata([xmin_new, xmax_new])

例如:
fig = plt.figure(figsize=(15, 13))
bp = sns.boxplot(#insert data and everything)
adjust_box_widths(fig, 0.9)

Example figure

关于python - 如何在seaborn boxplot中的相同子组之间创建间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56838187/

相关文章:

python - Django 测试 : Faking User Creation

python - 在具有多个子图的seaborn散点图上叠加一条垂直线

python - 确定 python 中的本地连接

Python:检测数字分隔符并解析为没有语言环境的 float

python - 将箱线图排列为带有 seaborn `FacetGrid` 的网格

使用 Seaborn 在散点图上绘制线条

r - 更改整条线的厚度geom_boxplot()

r - R中来自未标记矩阵的多个箱线图?

pandas - 如何从频率表创建箱线图

python - 派克达/CUDA : Causes of non-deterministic launch failures?