matplotlib畫概率直方圖概率之和不爲1

比如使用如下代碼畫一個概率直方圖:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'YC'
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

fig, ax = plt.subplots()

# histogram our data with numpy
data = np.random.randn(1000)
'''
得到的是數量統計
'''
n, bins = np.histogram(data, 50,normed=True)
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n


# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T

# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)

# make a patch out of it
patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='gray', alpha=0.8)
ax.add_patch(patch)

# update the view limits
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
#plt.xlabel('Smarts')
#plt.ylabel('Probability')
print(os.getcwd())
plt.savefig(os.getcwd()+"/histogram.png")
plt.show()


結果發現概率之和不爲1,解決辦法就是重新normalized 各個bins返回的值:

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'YC'
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

fig, ax = plt.subplots()

# histogram our data with numpy
data = np.random.randn(1000)
'''
得到的是數量統計
'''
n, bins = np.histogram(data, 50,normed=True)

'''
renormalized the hist values to make the integral probability equal to 1
'''
n = n*np.diff(bins)

# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n


# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T

# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)

# make a patch out of it
patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='gray', alpha=0.8)
ax.add_patch(patch)

# update the view limits
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
#plt.xlabel('Smarts')
#plt.ylabel('Probability')
print(os.getcwd())
plt.savefig(os.getcwd()+"/histogram.png")
plt.show()


 


發佈了178 篇原創文章 · 獲贊 7 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章