繁体   English   中英

如何在seaborn barplot上设置宽度

[英]how to set width on seaborn barplot

我想设置在基于列的次数的每barplot条的宽度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'

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

虽然在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()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM