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

2024-09-29 20:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个seaborn box情节,看起来像这样: 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')

有没有办法在三组人之间创造一个小空间,使他们不互相接触?在


Tags: 代码boxdataseabornall色调huevalues
1条回答
网友
1楼 · 发布于 2024-09-29 20:23:52

我找到了另一个用户发布的解决方案。此函数用于根据您选择的系数调整所创建地物中所有对象的宽度

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

例如:

^{pr2}$

Example figure

相关问题 更多 >

    热门问题