Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove gaps between bars in Matplotlib bar chart

I'm making a bar chart in Matplotlib with a call like this:

xs.bar(bar_lefts, bar_heights, facecolor='black', edgecolor='black') 

I get a barchart that looks like this:

Bar chart with gaps

What I'd like is one with no white gap between consecutive bars, e.g. more like this:

enter image description here

Is there a way to achieve this in Matplotlib using the bar() function?

like image 992
Bryce Thomas Avatar asked Dec 08 '13 13:12

Bryce Thomas


People also ask

Do bar charts have gaps between bars?

A standard bar chart should have gaps between bars that are slightly narrower than the bars. The exceptions to this are the exception of histograms and clustered bar charts.

Why do some bar charts have gaps?

A histogram is designed without gaps between the bars to indicate where one range ends and the next begins. If your data does not have a natural ordering and is categorical, then a bar chart with gaps between the bars may be the graph for you.


2 Answers

Add width=1.0 as a keyword argument to bar(). E.g.

xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black').

This will fill the bars gaps vertically.

like image 88
George Avatar answered Sep 26 '22 14:09

George


It has been 8 years since this question was asked, and the matplotlib API now has built-in ways to produce filled, gapless bars: pyplot.step() and pyplot.stairs() with the argument fill=True.

See the docs for a fuller comparison, but the primary difference is that step() defines the step positions with N x and N y values just like plot() would, while stairs() defines the step positions with N heights and N+1 edges, like what hist() returns. It is a subtle difference, and I think both tools can create the same outputs.

like image 24
Trenton Avatar answered Sep 24 '22 14:09

Trenton