如何重新调整 matplotlib 直方图中的计数

8

我有一个工作正常的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倍。我不想改变直方图的宽度,也不想改变y轴标签。我想要把所有bin里的计数(例如,bin 1有17个计数)乘以2,这样bin 1现在就有34个计数。

这个可行吗?

谢谢。

2个回答

7

由于这只是对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()

6

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接