【问题标题】:How to create spacing between same subgroup in seaborn boxplot?如何在seaborn boxplot中的同一子组之间创建间距?
【发布时间】:2019-07-09 23:24:31
【问题描述】:

我目前有一个如下所示的 seaborn 箱线图:

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 组之间创造一个小空间,使它们不会相互接触?

【问题讨论】:

  • 使用 matplotlib 箱线图作为例如here.
  • 只要扩大你的情节,它就会自行调整。
  • @steven 没用

标签: python seaborn boxplot


【解决方案1】:

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

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)

【讨论】:

  • 需要进行哪些更改才能使其适用于水平箱线图?
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
相关资源
最近更新 更多