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?
To set width for bars in Bar Plot drawn using barplot() function, pass the required width value for width parameter in the function call.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With