Python: Histogram with area normalized to something other than 1

后端 未结 2 1359
感动是毒
感动是毒 2021-01-02 08:21

Is there a way to tell matplotlib to \"normalize\" a histogram such that its area equals a specified value (other than 1)?

The option \"normed = 0\" in



        
2条回答
  •  臣服心动
    2021-01-02 08:52

    You can pass a weights argument to hist instead of using normed. For example, if your bins cover the interval [minval, maxval], you have n bins, and you want to normalize the area to A, then I think

    weights = np.empty_like(x)
    weights.fill(A * n / (maxval-minval) / x.size)
    plt.hist(x, bins=n, range=(minval, maxval), weights=weights)
    

    should do the trick.

    EDIT: The weights argument must be the same size as x, and its effect is to make each value in x contribute the corresponding value in weights towards the bin count, instead of 1.

    I think the hist function could probably do with a greater ability to control normalization, though. For example, I think as it stands, values outside the binned range are ignored when normalizing, which isn't generally what you want.

提交回复
热议问题