按键值的顺序绘制python dict
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37266341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting a python dict in order of key values
提问by DJname
I have a python dictionary that looks like this:
我有一个看起来像这样的python字典:
In[1]: dict_concentration
Out[2] : {0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
They keys are type int, the values are type float64.
Unfortunately, when I try to plot this with lines, matplotlib connects the wrong points (plot attached). How can I make it connect lines in order of the key values?
它们的键是 int 类型,值是 float64 类型。不幸的是,当我尝试用线条绘制它时,matplotlib 连接了错误的点(附上图)。我怎样才能让它按键值的顺序连接线?
回答by SparkAndShine
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
Python 字典是无序的。如果你想要一个有序的字典,使用collections.OrderedDict
In your case, sort the dict by key before plotting,
在您的情况下,在绘图之前按键对 dict 进行排序,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
回答by mhawke
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
只需将排序的项目从字典传递给plot()
函数。concentration.items()
返回一个元组列表,其中每个元组包含字典中的一个键及其对应的值。
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
您可以利用列表解包(使用*
)将排序后的数据直接传递给 zip,然后再次将其传递给plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
sorted()
按元组项的顺序对元组进行排序,因此您无需指定key
函数,因为 返回的元组dict.item()
已经以键值开头。