2017-10-16 538 views
1

我想创建一个可变宽度x轴箱子在Seaborn条形图。与此图表类似: enter image description here 我所有的宽度都会加起来达到100%,但我似乎无法找到如何通过Seaborn完成此目标的示例。有任何想法吗?可变宽度barplot与seaborn

+0

没有理由使用seaborn条形图用于这一目的。改为使用'pyplot.bar'。 – ImportanceOfBeingErnest

回答

1

这里可能有几个可能的答案。在seaborn barplot中,可以使用几个参数的组合:“宽度”(条的宽度值),“左”(x轴上的位置值,这是强制参数)和“对齐”。

一个非常简单的例子:

import seaborn as sns 

data = [7, 3, 15] 
widths = [1, 5, 3] 
left = [0, 1, 6] 
sns.plt.bar(left, data, width = widths, color=('orange','green','blue'), 
alpha = 0.6, align='edge', edgecolor = 'k', linewidth = 2) 

注意,“左”(酒吧位置)应当对应于宽度,以使杆到刚好接触和不重叠。

enter image description here

+0

通过使用'sns.plt.bar',你可以调用matplotlibs'plt.bar'函数。这与海豹无关。 – ImportanceOfBeingErnest

0

如果你想使用Seaborn为barplot,您需要更改的吧矩形的宽度(补丁)之后(这是通过matplotlib面向对象接口,完成按this answer):

import seaborn as sns 

iris = sns.load_dataset('iris') 
ax = sns.barplot('species', 'sepal_width', data=iris) 
widthbars = [0.3, 0.6, 1.2] 
for bar, newwidth in zip(ax.patches, widthbars): 
    x = bar.get_x() 
    width = bar.get_width() 
    centre = x + width/2. 
    bar.set_x(centre - newwidth/2.) 
    bar.set_width(newwidth) 

enter image description here

你也可以在matplotlib创建一个类似barplot直接:

import matplotlib.pyplot as plt 

widths = [0.3, 0.6, 1.2] 
for x_pos, (species_name, species_means) in enumerate(iris.groupby('species').mean().groupby('species')): 
    plt.bar(x_pos, species_means['sepal_width'], widths[x_pos]) 

enter image description here