【问题标题】:How can I compute the area under a histogram after a certain value?如何计算某个值后直方图下的面积?
【发布时间】:2015-12-01 02:43:01
【问题描述】:

我正在使用它来计算整个直方图下的面积。但是,我找不到说明如何在某个值之后或特定间隔内计算直方图下面积的资源。请对此有任何想法吗? x 是我的数据,值是发生的概率。

area = sum(np.diff(bins)*values)

【问题讨论】:

    标签: python numpy histogram


    【解决方案1】:

    我相信np.diff(bins) 是一维 numpy 数组,在这种情况下,您可以将其切片为 np.diff(bins)[start:end],并将 np.diff(bins)[start:] 切片为某事之后的所有值。

    【讨论】:

      【解决方案2】:
      area = sum(np.diff(bins)[0]*values[start:])
      

      np.diff(bins) 帮助您找到x 的部分,沿 x 轴方向相同。因此,您可以取第一个元素。

      【讨论】:

        【解决方案3】:

        使用A.Rauan's的方法,这里是一个直方图和某个值之后的区域的可视化:

        import numpy as np
        import matplotlib.pyplot as plt
        
        
        def find_bin_idx_of_value(bins, value):
            """Finds the bin which the value corresponds to."""
            array = np.asarray(value)
            idx = np.digitize(array,bins)
            return idx-1
        
        def area_after_val(counts, bins, val):
            """Calculates the area of the hist after a certain value"""
            left_bin_edge_index = find_bin_idx_of_value(bins, val)
            bin_width = np.diff(bins)[0]
            area = sum(bin_width * counts[left_bin_edge_index:])
            return area
        
        def add_area_line_to_plot(axes, counts, bins, val):
            """Adds a vertical line and labels it with the value and area after that line"""
            area = area_after_val(counts, bins, val)
            axes.axvline(val, color='r', label=f"val={val:.2f}, Area={area:.2f}")
        
        
        def main():
            num_data_points, loc, scale = 1000, 40, 20
            data = np.random.normal(loc, scale,num_data_points)
            fig, ax = plt.subplots()
            counts, bins, _ = ax.hist(data, bins=20, alpha=0.3, density=True, label="Data")
            add_area_line_to_plot(ax, counts, bins, val=min(data))
            add_area_line_to_plot(ax, counts, bins, val=np.mean(data))
            add_area_line_to_plot(ax, counts, bins, val=np.mean(data)*2)
            add_area_line_to_plot(ax, counts, bins, val=np.mean(data)*3)
            ax.legend()
            plt.show()
        
        if __name__ == "__main__":
            main()  
        
        

        【讨论】:

          猜你喜欢
          • 2020-10-15
          • 2021-05-25
          • 1970-01-01
          • 1970-01-01
          • 2019-02-11
          • 2020-09-15
          • 1970-01-01
          • 2011-01-22
          • 2010-11-26
          相关资源
          最近更新 更多