如何在seaborn barplot上设置宽度 [英] how to set width on seaborn barplot

查看:651
本文介绍了如何在seaborn 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()为关键字参数'width'获得了多个值

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

解决方案

虽然在seaborn中没有内置方法可以执行此操作,但是您可以操纵 sns.barplot 在matplotlib 轴对象.

根据

I would like to set the width of each bar on the barplot based on the number of times the column chrom has a particular value. I am setting width bars to be a list of occurrences:

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

widthbars = list_counts.tolist()

Plotting the barplot as:

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

This gives me an error:

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

Is the width variable being set somewhere implicitly? How do I get the widths of each bar to be different?

解决方案

While there is no built-in way to do this in seaborn, you can manipulate the patches that sns.barplot creates on the matplotlib axes object.

Here is a minimal example for how to do it, based on the seaborn example for barplot here.

Note that each bar is allotted a space that is 1 unit wide, so it is important to normalise your counts to the interval 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()

这篇关于如何在seaborn barplot上设置宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆