How to remove gaps between bars in Matplotlib bar chart
Question:
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:
What I’d like is one with no white gap between consecutive bars, e.g. more like this:
Is there a way to achieve this in Matplotlib using the bar()
function?
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.
Just set the width 1 over the number of bars, so:
width = 1 / len(bar_lefts)
xs.bar(bar_lefts, bar_heights, width=width, color='black')
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.
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:
What I’d like is one with no white gap between consecutive bars, e.g. more like this:
Is there a way to achieve this in Matplotlib using the bar()
function?
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.
Just set the width 1 over the number of bars, so:
width = 1 / len(bar_lefts)
xs.bar(bar_lefts, bar_heights, width=width, color='black')
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.