【问题标题】:Python Stacked Barchart from Counter using matplotlib使用 matplotlib 来自 Counter 的 Python Stacked Barchart
【发布时间】:2017-08-20 22:01:46
【问题描述】:

我有一个大的 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()

但是,它返回错误消息:

ValueError:不兼容的尺寸:参数“高度”的长度必须为 4 或 标量

我认为这与ind 数组有关。

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

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

获得的结果:

预期结果:

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

【问题讨论】:

    标签: python python-2.7 matplotlib counter bar-chart


    【解决方案1】:

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

    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 上提供的帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2021-01-26
      • 2017-09-20
      • 2022-06-14
      • 1970-01-01
      相关资源
      最近更新 更多