Is there a clean way to generate a line histogram chart in Python?

后端 未结 3 520
庸人自扰
庸人自扰 2021-02-01 07:01

I need to create a histogram that plots a line and not a step or bar chart. I am using python 2.7 The plt.hist function below plots a stepped line and the bins don\'t line up i

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 07:51

    The line plot you are producing does not line up as the x values being used are the bin edges. You can calculate the bin centers as follows: bin_centers = 0.5*(x[1:]+x[:-1]) Then the complete code would be:

    noise = np.random.normal(0,1,(1000,1))
    n,x,_ = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' )
    bin_centers = 0.5*(x[1:]+x[:-1])
    plt.plot(bin_centers,n) ## using bin_centers rather than edges
    plt.show()
    

    If you want the plot filled to y=0 then use plt.fill_between(bin_centers,n)

提交回复
热议问题