python显示归一化后的直方图

it2022-05-05  149

在使用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"))

 


最新回复(0)