Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set width on seaborn barplot

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?

like image 327
Preethi Avatar asked Apr 24 '16 14:04

Preethi


People also ask

How do you change the width of a barplot?

To set width for bars in Bar Plot drawn using barplot() function, pass the required width value for width parameter in the function call.

How do you increase the size of the barplot in Seaborn?

Set the figsize argument in matplotlib. Save the result to a figure and an axes variable. When creating the Seaborn plot, call seaborn. barplot(ax=None) and set ax equal to the axes variable to change the figure size.


1 Answers

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

enter image description here

like image 180
tmdavison Avatar answered Sep 20 '22 09:09

tmdavison