1

I was trying to draw a histogram of a sine curve as below

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

dt=0.01 #delta t
T_upper=100. #time upper limit
t=np.arange(0.,T_upper+dt,dt) #time
#print t[-1]
a=2. #wave amplitude
T=2. #wave period
phi=np.pi/2 #phase
eta=a*np.sin(2*np.pi/T*t+phi)
#plt.plot(t,eta)

plt.hist(eta,normed=True,bins=20,color='blue',edgecolor='black',linewidth=1)
plt.ylabel('Probability')
plt.xlim(eta.min()*1.25,eta.max()*1.25)
plt.xticks([-2,-1,0,1,2])
plt.show()

And below is what I get enter image description here

It can be seen that bins do not align with their values. What I want is to have bins locate at the centre of their values, for example at min, -2 and max 2.

I tried using bins=np.arange(2)-0.5, it does not work for me, I think it is because of the interval of this histogram is not integers, but I am not sure how to fix it, can anyone help, thanks in advance.

Zhifang Hu
  • 241
  • 1
  • 3
  • 8
  • duplicate of https://stackoverflow.com/questions/23246125/how-to-center-labels-in-histogram-plot – aless80 Dec 10 '19 at 15:44

1 Answers1

0

You need to specify align parameter, for example:

plt.hist(eta, align='mid')

Here are the docs.

Gerges
  • 6,269
  • 2
  • 22
  • 44
  • Hi there, I've tried the align comment before, but it gives me the same plot, bins are not located at the centre of the numbers. – Zhifang Hu Oct 09 '17 at 23:43
  • Sorry my bad. In the example I gave the bins will be centered in the middle of intervals. For example, in the figure, the first bin to the left is the # of values between -2 and -1.8. So `align='mid'` will put the bin around -1.9. If you say align=`left`, the bin will be around -2. – Gerges Oct 10 '17 at 00:26
  • Hi there, I dont think align='left' would work either, I tried that before, basically it shifts the whole graph to the left, where the -2 bin is aligned at the centre, the the positive 2 is completely off as there is no bins there. – Zhifang Hu Oct 11 '17 at 23:27