使用matplotlib从计数器中选择Python堆叠条形图
我有一个大的csv文件。读取此文件,并每隔预定义行数返回一个使用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
计数器。例如:
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于年月日提供的帮助