在Python Graphs中使用Seaborn生成嵌套框图中的箱形图之间的空间?

kev*_*vin 6 python matplotlib boxplot seaborn

我试图在用Python Seaborn模块创建的箱形图(绿色和橙色框之间)之间设置一个空格sns.boxplot().请参见附图,绿色和橙色子图框相互粘连,使其在视觉上不是最吸引人的.

无法找到办法做到这一点,任何人都可以找到办法(代码附加)?

Seaborn Boxplots

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
sns.set(style="ticks", palette='Set2', font='Roboto Condensed')
sns.set_context("paper", font_scale=1.1, rc={"lines.linewidth": 1.1})
g=sns.factorplot(x="time", y="total_bill", hue="smoker",
               col="day", data=tips, kind="box", size=4, aspect=0.5,
                 width=0.8,fliersize=2.5,linewidth=1.1, notch=False,orient="v")
sns.despine(trim=True)
g.savefig('test6.png', format='png', dpi=600)
Run Code Online (Sandbox Code Playgroud)

Seaborn箱线图文档是在这里:http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.boxplot.html

Tho*_*ühn 2

冒着不再需要这个的危险,我找到了解决这个问题的方法。直接使用 matplotlib绘图时,可以使用和关键字boxplots控制框的排列。然而,当将关键字传递给时,会得到一个widthpositionpositionssns.factorplot(kind='box',...)

TypeError: boxplot() got multiple values for keyword argument 'positions'
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,可以在创建箱线图后“手动”设置框的宽度。这有点乏味,因为这些框存储在所返回的 的PatchPatches各个Axes实例中。使用顶点来定义角,而不是使用简单的语法,当想要调整框时,这会涉及更多的计算。最重要的是,返回的 by包含一个额外的(被忽略的)代码顶点,该顶点被设置为并且最好被忽略。除了方框之外,标记中位数的水平线现在也太宽,也需要调整。FacedGridsns.factorplot(x,y,width,height)RectsPathPatchesPathPatchesmatplotlib.boxplotPath.CLOSEPOLY(0,0)

下面我定义了一个函数来调整OP示例代码生成的框的宽度(注意额外的导入):

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.flatten():

        ##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])
Run Code Online (Sandbox Code Playgroud)

调用这个函数

adjust_box_widths(g, 0.9)
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

调整框宽度的seaborn箱线图