如何在seaborn barplot上设置宽度

Pre*_*thi 6 python matplotlib seaborn

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

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

widthbars = list_counts.tolist()
Run Code Online (Sandbox Code Playgroud)

将条形图绘制为:

ax = sns.barplot(x = plot_data['chrom'], y = plot_data['dummy'], width=widthbars)
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

TypeError: bar() got multiple values for keyword argument 'width'
Run Code Online (Sandbox Code Playgroud)

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

tmd*_*son 11

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

这是一个如何做的最小例子,基于这里barplot的seaborn示例.

请注意,每个条形图被分配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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 好的。因为问题是关于对宽度使用计数测量,所以我会提到每个条形都分配有 1 个单位宽的空间,因此最好对宽度测量添加某种归一化,否则绘图将是无法解释的。 (2认同)