How to center marks in a bar chart

I have a numpy results array that looks like

 [ 0. 2. 0. 0. 0. 0. 3. 0. 0. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 2. 0. 3. 1. 0. 0. 2. 2. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 3. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 2. 2.] 

I would like to plot a histogram. I tried

 import matplotlib.pyplot as plt plt.hist(results, bins=range(5)) plt.show() 

This gives me a histogram with the x axis labeled 0.0 0.5 1.0 1.5 2.0 2.5 3.0. 3.5 4.0 0.0 0.5 1.0 1.5 2.0 2.5 3.0. 3.5 4.0 .

I would like the x axis to be labeled 0 1 2 3 instead of the labels in the center of each bar. How can you do this?

+7
python numpy matplotlib histogram
source share
3 answers

The following alternative solution is compatible with plt.hist() (and this has the advantage that you can call it after pandas.DataFrame.hist() .

 import numpy as np def bins_labels(bins, **kwargs): bin_w = (max(bins) - min(bins)) / (len(bins) - 1) plt.xticks(np.arange(min(bins)+bin_w/2, max(bins), bin_w), bins, **kwargs) plt.xlim(bins[0], bins[-1]) 

(The last line is not strictly requested by the OP, but makes it more enjoyable)

This can be used as in:

 import matplotlib.pyplot as plt bins = range(5) plt.hist(results, bins=bins) bins_labels(bins, fontsize=20) plt.show() 

Result: success!

+4
source share

you can plot a bar chart from np.histogram .

Consider this

 his = np.histogram(a,bins=range(5)) fig, ax = plt.subplots() offset = .4 plt.bar(his[1][1:],his[0]) ax.set_xticks(his[1][1:] + offset) ax.set_xticklabels( ('1', '2', '3', '4') ) 

enter image description here

EDIT: to make the strokes touch each other, you need to play with the width parameter.

  fig, ax = plt.subplots() offset = .5 plt.bar(his[1][1:],his[0],width=1) ax.set_xticks(his[1][1:] + offset) ax.set_xticklabels( ('1', '2', '3', '4') ) 

enter image description here

+5
source share

Other answers just don't do this for me. The advantage of using plt.bar over plt.hist is that the bar can use align='center' :

 import numpy as np import matplotlib.pyplot as plt arr = np.array([ 0., 2., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 2., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 2., 0., 3., 1., 0., 0., 2., 2., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 2., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 2., 2.]) labels, counts = np.unique(arr, return_counts=True) plt.bar(labels, counts, align='center') plt.gca().set_xticks(labels) plt.show() 

histogram label centering

+3
source share

All Articles