如何在seaborn barplot上设置宽度

时间:2016-04-24 14:14:29

标签: python matplotlib seaborn

我想根据列chrom具有特定值的次数来设置条形图上每个条的宽度。 我将宽度条设置为出现列表:

list_counts =  plot_data.groupby('chrom')['gene'].count()

widthbars = list_counts.tolist()

将条形图绘制为:

ax = sns.barplot(x = plot_data['chrom'], y = plot_data['dummy'], width=widthbars)

这给了我一个错误:

TypeError: bar() got multiple values for keyword argument 'width'

宽度变量是否隐式设置在某处? 如何让每个条的宽度不同?

1 个答案:

答案 0 :(得分:6)

虽然在seaborn中没有内置方法可以执行此操作,但您可以操作sns.barplot在matplotlib轴对象上创建的修补程序。

以下是基于seaborn example for barplot here

的最佳示例

请注意,每个条形图被分配1个单位宽的空间,因此将计数标准化为0-1区间非常重要。

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.barplot(x="day", y="total_bill", data=tips)

# Set these based on your column counts
columncounts = [20,40,60,80]

# Maximum bar width is 1. Normalise counts to be in the interval 0-1. Need to supply a maximum possible count here as maxwidth
def normaliseCounts(widths,maxwidth):
    widths = np.array(widths)/float(maxwidth)
    return widths

widthbars = normaliseCounts(columncounts,100)

# Loop over the bars, and adjust the width (and position, to keep the bar centred)
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)

plt.show()

enter image description here