Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force bins with zero-height in matplotlib bar plot

Consider the following script:

import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
pylab.bar(*zip(*enumerate(counts)), align='center')
pylab.show()

When I run this I get the following image. barchart

As you can see the 0-height bins at the edges of the plot are not plotted. However, I want them indeed to be plotted. What can I do to achieve this?

I know that I can set the x_lim of the axes (Axes.set_xlim). If no other option exists, what approach takes most elegantly into account the width of the bars?

like image 692
moooeeeep Avatar asked Apr 18 '12 14:04

moooeeeep


2 Answers

One way would be something similar to the following:

import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
artists = pylab.bar(*zip(*enumerate(counts)), align='center')

lefts = [item.get_x() for item in artists]
rights = [item.get_x() + item.get_width() for item in artists]
pylab.xlim([min(lefts), max(rights)])

pylab.show()

enter image description here

like image 161
Joe Kington Avatar answered Sep 27 '22 22:09

Joe Kington


Found another solution that may be working more reliably than set_xlim:

import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
# add a epsilon to counts to force bins to be plotted
epsilon = 1e-7
counts = [x+epsilon for x in counts]
pylab.bar(*zip(*enumerate(counts)), align='center')
pylab.show()

barchart

like image 22
moooeeeep Avatar answered Sep 27 '22 20:09

moooeeeep