Seaborn: Adding space between boxes in grouped boxplot

Created on 10 Dec 2016  Â·  9Comments  Â·  Source: mwaskom/seaborn

Is there an easy way, either through seaboard or matplotlib directly, to add some space between boxes in a grouped box plot?

For example, add a bit of space between pink and green boxes in this example.

Most helpful comment

Is there still a solution for adding space between the boxes within the group?

All 9 comments

I don't think so, sorry.

@agamemnonc you can make the boxes narrower using width:

# Draw a nested boxplot to show bills by day and sex
sns.boxplot(x="day", y="total_bill", hue="sex", data=tips, palette="PRGn", width=0.2)
sns.despine(offset=10, trim=True)

boxes

Yes, good point — I had assumed @agamemnonc meant between the boxes in each group.

re-reading the question, I think that's the safer assumption

Indeed, I meant space between the boxes within the same group

Is there still a solution for adding space between the boxes within the group?

Is there any update about this issue/question ?

I found a solution here.

import numpy as np
from matplotlib.patches import PathPatch

def adjust_box_widths(g, fac):
    """
    Adjust the widths 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])

For example

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

It would be great if seaborn had an internal solution for this... How about re-opening the issue? (not sure why it was closed?)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chanshing picture chanshing  Â·  3Comments

queryous picture queryous  Â·  4Comments

sungshine picture sungshine  Â·  3Comments

amelio-vazquez-reina picture amelio-vazquez-reina  Â·  4Comments

tritemio picture tritemio  Â·  3Comments