2017-10-16 540 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