40

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Bryce Thomas
  • 10,479
  • 26
  • 77
  • 126

4 Answers4

59

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.

Bryce Thomas
  • 10,479
  • 26
  • 77
  • 126
George
  • 5,808
  • 15
  • 83
  • 160
  • `width=?`. The snippet above breaks as width isn't being given as a keyword argument but rather as a variable (which doesn't exist). – Bryce Thomas Dec 09 '13 at 13:30
  • @Bryce Thomas:If you just write width ,it takes as width=1 I think (to me it works).So,with width=1 ,does it work as you wanted? – George Dec 09 '13 at 15:18
  • Fair enough, I'm surprised it works at all on your end. On my system it's (almost) a syntax error, as the language is interpreting width to be a non-named parameter, and it can't find any variable named width in my program obviously. Yep, width=1 seems to do what I wanted. – Bryce Thomas Dec 09 '13 at 15:36
  • Setting `linewidth=0.0` and `width=1.0` will remove the bar edge line. This has removed the (visually appearing grey) space between bars in my case of 10000+ data points. – pds Mar 06 '15 at 20:39
6

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.

Trenton
  • 331
  • 3
  • 4
  • Thanks. Bar can work but it leaves some barely visible gaps in the saved pdf even with bar width set to 1. – Yiding Sep 09 '21 at 04:24
1

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')
Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29
0

You can set the width equal to the distance between two bars:

width = bar_lefts[-1] - bar_lefts[-2]
xs.bar(bar_lefts, bar_heights, width=width)
ekraus
  • 124
  • 4