【问题标题】:How to re-scale the counts in a matplotlib histogram如何重新缩放 matplotlib 直方图中的计数
【发布时间】:2019-07-14 09:43:24
【问题描述】:

我有一个运行良好的 matplotlib 直方图。

hist_bin_width = 4
on_hist = plt.hist(my_data,bins=range(-100, 200,hist_bin_width),alpha=.3,color='#6e9bd1',label='on')

我想要做的只是重新缩放一个因子,比如 2。我不想更改 bin 宽度,也不想更改 y 轴标签。我想计算所有箱中的计数(例如箱 1 有 17 个计数)并乘以 2,以便箱 1 现在有 34 个计数。

这可能吗?

谢谢。

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    因为这只是对 y 轴的简单重新缩放,所以这一定是可能的。出现复杂情况是因为 Matplotlib 的 hist 计算 绘制直方图,因此难以干预。但是,正如文档还指出的那样,您可以使用 weights 参数来“绘制已经分箱的数据的直方图”。您可以在第一步中使用 Numpy 的 histogram 函数对数据进行分类。应用比例因子就很简单了:

    from matplotlib import pyplot
    import numpy
    
    numpy.random.seed(0)
    data = numpy.random.normal(50, 20, 10000)
    (counts, bins) = numpy.histogram(data, bins=range(101))
    
    factor = 2
    pyplot.hist(bins[:-1], bins, weights=factor*counts)
    pyplot.show()
    

    【讨论】:

      【解决方案2】:

      pyplot.histweights 参数可用于对每个数据点进行加权,例如

      import matplotlib.pyplot as plt
      import numpy as np; np.random.seed(42)
      
      data = np.random.normal(50, 20, 10000)
      
      factor = 2
      hist_bin_width = 40
      plt.hist(data, bins=range(-100, 200, hist_bin_width), 
                     weights=factor*np.ones_like(data))
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-19
        • 2021-10-21
        • 2017-02-18
        • 1970-01-01
        • 1970-01-01
        • 2020-03-09
        • 2021-12-28
        • 2015-09-02
        相关资源
        最近更新 更多