Python 使用 matplotlib 来自计数器的堆叠条形图

Python Stacked Barchart from Counter using matplotlib

我有一个很大的 csv 文件。读取此文件并返回每个预定义行数的 Counter。例如:

counter = [Counter({(0, 1): 9, (1, 2): 8}), Counter({(1, 2): 99, (0, 1): 99}), Counter({(1, 2): 256, (0, 1): 189}), Counter({(1, 5): 473, (0, 1): 301})]

这是我使用的脚本。

import matplotlib.pyplot as plt
import numpy
from collections import Counter
counter = [Counter({(0, 1): 9, (1, 2): 8}), Counter({(1, 2): 99, (0, 1): 99}), Counter({(1, 2): 256, (0, 1): 189}), Counter({(1, 5): 473, (0, 1): 301})]

fig = plt.figure()
ax1 = fig.add_subplot(111)

N = len(counter)
ind = numpy.arange(N)

j = 0
while j in range(0, len(counter)):
    a, i = 0, 0
    frequencies = counter[j].values()
    names = counter[j].keys()
    while i in range(0, len(frequencies)):
        if i == 0:
            ax1.bar(ind, frequencies[i], label=names[i], width=0.25)
            a = frequencies[i]
        else:
            ax1.bar(ind, frequencies[i], label=names[i], width=0.25, bottom=a)
            a += frequencies[i]
        i += 1
    j += 1
labels = ["%s to %s" % (200, 202)]
ax1.set_xticks(numpy.arange(N))
ax1.set_xticklabels(labels)
ax1.set_ylabel("Frequency")
ax1.set_xlabel("Material Contact")
ax1.legend()

plt. show()

然而,它returns作为错误信息:

ValueError: incompatible sizes: argument 'height' must be length 4 or scalar

我认为这与 ind 数组有关。

为了克服这个问题,我将 if 语句中的 ind 更改为 ind[j]。然而,最终的结果是有很多带有很多颜色的条。正如预期的那样,颜色与其各自的 bin 无关。

ax1.bar(ind[j], frequencies[i], label=names[i], width=0.25)

得到的结果:

预期结果:

更新: 一个可能的解决方案是从计数器构建一个数组。但是,这首先违背了计数器的概念。

所以唯一的答案是重新评估和重组数据

series = {}
for key in {key for keys in counter for key in keys}:
    series[key] = [(0 if key not in item else item[key]) for item in counter]

感谢 zivoni 在 python-forum

上提供的帮助