Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用matplotlib从计数器中选择Python堆叠条形图_Python_Python 2.7_Matplotlib_Counter_Bar Chart - Fatal编程技术网

使用matplotlib从计数器中选择Python堆叠条形图

使用matplotlib从计数器中选择Python堆叠条形图,python,python-2.7,matplotlib,counter,bar-chart,Python,Python 2.7,Matplotlib,Counter,Bar Chart,我有一个大的csv文件。读取此文件,并每隔预定义行数返回一个计数器。例如: counter=[计数器({(0,1):9,(1,2):8}),计数器({(1,2):99,(0,1):99}),计数器({(1,2):256,(0,1):189}),计数器({(1,5):473,(0,1):301})] 这是我使用的脚本 import matplotlib.pyplot as plt import numpy from collections import Counter counter = [Cou

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

counter=[计数器({(0,1):9,(1,2):8}),计数器({(1,2):99,(0,1):99}),计数器({(1,2):256,(0,1):189}),计数器({(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:大小不兼容:参数“height”的长度必须为4或 标量

我认为这与
ind
数组有关

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

获得的结果:

预期结果:

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

因此,唯一的答案是重新评估和重组数据

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在

上提供的帮助,因此唯一的答案是重新评估和重组数据

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于年月日提供的帮助