我在 Python 2.7 :
中有以下词典packetsNeeded = {
'Hydrogen': 142,
'Helium': 122,
'Lithium': 135,
'Boron': 145,
'Beryllium': 135,
'Nitrogen': 171,
'Neon': 141,
'Oxygen': 134,
'Carbon': 239,
'Florine': 134
}
我编写了一个脚本,我在其中绘制了所需数据包与dict键的水平条形图。
代码很简单,如下:
from pylab import *
pos = arange(10)+.5
barh(pos, packetsNeeded.values(), align = 'center', color = 'green')
yticks(pos, (packetsNeeded.keys()))
for i, v in enumerate(packetsNeeded.values()):
text(v + 3, i + .25, str(v), fontweight = 'bold', fontsize = '15')
xlim(0, 300)
grid(True)
show()
输出非常好,非常棒:
如何将yticks
精确提及的packetsNeeded
作为Beryllium: 135
dict中的键序列?如您所见,第一个图表条目为Hydrogen: 142
,而packetsNeeded
字典中为scatterplot3d
。
图表中的排序又如何?我还没有在代码中的任何地方提到任何排序?
答案 0 :(得分:0)
感谢@Tim建议将数据收集为元组列表,
答案可能是字典没有在内存中排序
现在,收集的数据表示为元组列表:
from pylab import *
## List of Tuples much better than dicts since dicts are not arranged
## in memory
packetsNeeded = [
('Hydrogen', 142),
('Helium', 122),
('Lithium', 135),
('Boron', 145),
('Beryllium', 135),
('Nitrogen', 171),
('Neon', 141),
('Oxygen', 134),
('Carbon', 239),
('Florine', 134)
]
创建一些列表推导以分隔值和名称:
## List Comprehensions for Names and Values
names = [packetsNeeded[item][0] for item in range(len(packetsNeeded))]
values = [packetsNeeded[item][1] for item in range(len(packetsNeeded))]
用于绘制水平条形图的其余代码
pos = arange(10)+.5
barh(pos, values, align = 'center', color = 'green')
yticks(pos,(names))
for i, v in enumerate(values):
text(v + 3, i + .25, str(v), fontweight = 'bold', fontsize = '15')
xlim(0, 300)
title('Number of Packets Needed by Each TWIN node in Multihop')
xlabel('Number of Droplets Needed')
ylabel('Name of TWIN nodes')
grid(True)
show()