python显示归一化后的直方图

在使用python进行绘制直方图的时候,首先想到的是使用matplotlib.pyplot.hist这一个函数。

matplotlib.pyplot.hist(x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)

但是,直接使用这个函数,绘制出来的直方图各个bin的轴坐标之和并不等于1。即使我们将density设置为True也不能解决这个问题。这可能是这个function的一个bug。因此,得另外想办法进行实现。这里,我自己写了一个绘制直方图的程序。代码也很简单,但是却实实在在地解决这个问题。

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


def plot_hist(save_img_path,hist_array,bins,xmin,xmax,save_figure_name,figure_title):

    '''This function is used to plot the histogram, and the sum of it is 1'''
    #save_img_path : the path where you want to save the image
    #hist_array : the array that you want to plot its histogram
    #bins : how many bins do you want to plot
    #xmin, xmax : the minimun and the maximum of the x-axis
    #save_figure_name : the image file name
    #figure_title : the figure title

    plt.figure()
    n,bin,patches = plt.hist(hist_array,bins,(xmin,xmax),density=True)
    plt.close()
    plt.figure()
    plot_hist = n/bins
    fontsize = 20
    plt.title(figure_title, fontsize=fontsize)
    manager = plt.get_current_fig_manager()#这两行代码只是把显示窗口设置为最大,如果报错,直接注销即可
    manager.resize(*manager.window.maxsize())
    x = np.arange(xmin,xmax,(xmax-xmin)/bins)
    plt.bar(x,plot_hist,align='center',width=(xmax-xmin)/bins)
    plt.savefig(os.path.join(save_img_path,save_figure_name+".png"))

 

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值