Matplotlib: Histogram with bars inside grid lines...how??
John Hunter
jdhunter at ace.bsd.uchicago.edu
Thu Mar 30 00:08:08 EST 2006
>>>>> "Enigma" == Enigma Curry <workbee at gmail.com> writes:
Enigma> pylab.xlim(0.5,6.5) should be:
Enigma> pylab.xlim(min_x-(bar_width/2),max_x+(bar_width/2))
Glad it's working better for you -- just a couple more smallish hints.
You might prefer to have your grid lines behind, rather than above the
bars. In that case create the subplot or axes with the axisbelow=True
kwarg. Despite the fact that you found the kwargs a little annoying
at first, you will probably come to love them. matplotlib makes very
heavy use of them and they are very useful since they allow matplotlib
to usually do the right things while exposing most of the settings to
you. Eg
plot(x, y,
linewidth=2, linestyle='--',
marker='o', markerfacecolor='r', markeredgecolor='g'
markeredgewith=2, markersize=10)
and so on. There are lots of properties you can set on almost every
command. Because noone wants to type all that, you can use aliases
plot(x, y, lw=2, ls='--', marker='o', mfc='r', mec='g', mew=2, ms=10)
Secondly, in your example, you are relying implicitly on matplotlib to
pick integer ticks for the xaxis. It's doing it right in this
example, but might prefer other tick locations for other examples
depending on your x_values. So set xticks explicitly.
Below is a slightly modified example showing these two ideas.
You also might want to consider joining the mailing list at
http://lists.sourceforge.net/mailman/listinfo/matplotlib-users
since you appear to be a little finicky about your figures :-)
def ryan_hist(data, bar_width, min_x, max_x):
"""
Create a frequency histogram over a continuous interval
min_x = the low end of the interval
max_x = the high end of the interval
bar_width = the width of the bars
This will correctly align the bars of the histogram
to the grid lines of the plot
"""
#Make histogram with bars of width .9 and center
#them on the integer values of the x-axis
bins = pylab.nx.arange(1-(bar_width/2),max(data))
pylab.subplot(111, axisbelow=True)
n,bins,patches = pylab.hist(data, bins, width=bar_width)
#Make Y axis integers up to highest n
pylab.yticks(pylab.arange(max(n)))
pylab.xticks(pylab.arange(max(n)+1))
pylab.axis('scaled')
pylab.xlim(min_x-(bar_width/2),max_x+(bar_width/2))
pylab.grid()
pylab.show()
More information about the Python-list
mailing list