how to set width on seaborn barplot

旧城冷巷雨未停 提交于 2019-12-18 16:54:45

问题


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?


回答1:


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()



来源:https://stackoverflow.com/questions/36824229/how-to-set-width-on-seaborn-barplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!