比如使用如下代码画一个概率直方图:
#!/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()