我正在尝试在使用Python Seaborn
模块的 sns.boxplot()
创建的框线图之间(绿色和橙色框之间)设置一个空间。请参见附图,绿色和橙色子图框彼此粘在一起,从视觉上看并不是最吸引人的。
无法找到一种方法,有人可以找到一种方法(附加代码)吗?
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)
Seaborn
箱线图文档在这里:http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.boxplot.html 最佳答案
冒着不再需要此危险的危险,我找到了解决此问题的方法。当直接使用matplotlib绘制boxplots
时,可以使用width
和position
关键字来控制框的排列。但是,将positions
关键字传递给sns.factorplot(kind='box',...)
时,会得到一个
TypeError: boxplot() got multiple values for keyword argument 'positions'
为了解决这个问题,可以在创建箱形图后“手动”设置框的宽度。这有点乏味,因为这些框以
PatchPatches
的形式存储在Axes
返回的FacedGrid
的各个sns.factorplot
实例中。 (x,y,width,height)
使用顶点来定义边角,而不是Rects
具有简单的PathPatches
语法,当要调整盒子时,涉及更多的计算。最重要的是,PathPatches
返回的matplotlib.boxplot
包含Path.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])
用
adjust_box_widths(g, 0.9)
给出以下输出:
关于python - 在Python Graph中的框线图之间设置空间使用Seaborn?生成的嵌套框线图?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31498850/