从Matplotlib中预先计数的数据绘制直方图

2024-06-20 12:09:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Matplotlib在预先计数的数据上绘制直方图。例如,假设我有原始数据

data = [1, 2, 2, 3, 4, 5, 5, 5, 5, 6, 10]

根据这些数据,我可以使用

pylab.hist(data, bins=[...])

绘制柱状图。

在我的例子中,数据已经预先计数,并表示为字典:

counted_data = {1: 1, 2: 2, 3: 1, 4: 1, 5: 4, 6: 1, 10: 1}

理想情况下,我希望将这个预先计数的数据传递给一个直方图函数,该函数允许我控制箱子宽度、绘图范围等,就好像我已经将原始数据传递给它一样。作为一种解决方法,我正在将我的计数扩展到原始数据中:

data = list(chain.from_iterable(repeat(value, count)
            for (value, count) in counted_data.iteritems()))

counted_data包含数百万个数据点的计数时,这是低效的。

有没有一种更简单的方法可以使用Matplotlib从我预先计算的数据生成直方图?

或者,如果最简单的方法是将预先装箱的数据条形图,是否有一种方便的方法将我的每项计数“汇总”为装箱计数?


Tags: 数据方法函数data原始数据matplotlibvaluecount
3条回答

也可以使用seaborn绘制直方图:

import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(list(counted_data.keys()), hist_kws={"weights":list(counted_data.values())})

您可以使用weights关键字参数来np.histgram(下面的plt.hist调用)

val, weight = zip(*[(k, v) for k,v in counted_data.items()])
plt.hist(val, weights=weight)

假设您只有整数作为键,您还可以直接使用bar

min_bin = np.min(counted_data.keys())
max_bin = np.max(counted_data.keys())

bins = np.arange(min_bin, max_bin + 1)
vals = np.zeros(max_bin - min_bin + 1)

for k,v in counted_data.items():
    vals[k - min_bin] = v

plt.bar(bins, vals, ...)

哪里。。。是你想要传递给bar(doc)的任何参数

如果要重新整理数据,请参见Histogram with separate list denoting frequency

我使用pyplot.histweights选项根据每个键的值对其进行加权,生成我想要的直方图:

pylab.hist(counted_data.keys(), weights=counted_data.values(), bins=range(50))

这使我可以依赖hist来重新整理数据。

相关问题 更多 >