Niv R. Niv R. - 4 months ago 14
Python Question

first and last bars on matplotlib histogram appear moved

I'm trying to create a histogram using these values:

[1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2]


The code I'm using is this

plt.hist(values, histtype='bar', color='green', alpha=0.5)
plt.title(library_name, fontsize=12)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)


And I get this histogram histogram with first and last bars poorly located

Does anyone know why are the first and last bars looks aside from their xtick? I tried using plt.margins function with no results.

Thank you very much

Answer

To get centre-aligned bins instead of left-aligned, use plt.hist(data, bins=np.arange(50)-0.5)

Example code:

import matplotlib.pyplot as plt
import numpy as np

values = [1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2,5,3,2,5, 1, 1, 4, 1, 1, 2, 1, 1,7,8,9,9,3,8,6, 2]

offset = 0.5

plt.hist(values,  bins=np.arange(1,np.max(values)+2)-offset, histtype='bar', color='green', alpha=0.5)
plt.title('library_name', fontsize=12)
plt.xlabel('xlabel')
plt.ylabel('ylabel')
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.show()