Seaborn箱线图单个箱间距

2024-04-25 17:34:40 发布

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

如何在seaborn boxplot中增加两个Specific框之间的间距?在tips数据集中,如何在不影响其他框的情况下修改Sat和Sun之间的间距。我已经在dataframe中包含了空列,但是通过这个解决方法,不可能控制间距。在

%matplotlib inline
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)

Tips Boxplot Example


Tags: 数据方法dataframematplotlib情况inlineseabornsat
2条回答

Seaborn不提供此功能(参见示例this issue)。打印框后,仍可以调整matplotlib:

ax = plt.gca()  # Or get the axis another way

def _reduce_box_width(artist, factor=.5):
    vertices = artist.get_path().vertices
    artist_width = vertices[1, 0] - vertices[0, 0]
    vertices[0, 0] += artist_width * (factor/2)
    vertices[1, 0] -= artist_width * (factor/2)
    vertices[2, 0] -= artist_width * (factor/2)
    vertices[3, 0] += artist_width * (factor/2)
    vertices[4, 0] += artist_width * (factor/2)

for artist in ax.artists:
    _reduce_box_width(artist, factor=.5)

def _reduce_horizontal_line_width(artist, factor=.5):
    vertices = artist.get_path().vertices
    artist_width = vertices[1, 0] - vertices[0, 0]
    vertices[0, 0] += artist_width * (factor/2)
    vertices[1, 0] -= artist_width * (factor/2)

horizontal_lines = [l for l in ax.lines
                    if len(l.get_path().vertices) != 0 and
                       l.get_path().vertices[0, 1] = = l.get_path().vertices[1, 1]]
for line in horizontal_lines:
    _reduce_horizontal_line_width(line)

ax.redraw_in_frame()

可能需要根据您的具体情况进行调整。在

据我所知,这在seaborn中是不可能的,因为它没有提供任何修改positions关键字的方法。另请参见this similar question。在

最简单的解决方法是使用不同的boxplot函数,例如pandas dataframes附带的函数:

bplot = tips.boxplot(by="day", column="total_bill", positions=[1,2,3,4.5])

当然,这个版本的风格远不及seaborn版本。在

幸运的是,matplotlib为那些愿意探索它们的人提供了无限的选择,因此可以通过相应地修改绘图的不同部分来创建类似于seaborn绘图的内容。在

这很接近:

^{pr2}$

enter image description here

相关问题 更多 >