按键值顺序绘制Python字典

67

我有一个类似于这样的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}

键的类型为int,值的类型为float64。不幸的是,当我尝试使用线条绘制时,matplotlib连接了错误的点(见附图)。我该如何使它按键值顺序连接线条?enter image description here

3个回答

128

Python字典是无序的。如果你想要一个有序的字典,请使用collections.OrderedDict

在您的情况下,在绘图之前按键对字典进行排序。

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()

这是结果。 这里输入图片描述


9
知道 "*" 可以拆包元组非常有用。 - rAntonioH
7
如果您想按值排序,请使用lists = sorted(d.items(), key=lambda kv: kv[1], reverse=True) - Bikash Gyawali

18

只需将字典中排序后的项目传递给plot()函数。 concentration.items()返回一个元组列表,其中每个元组包含字典的一个键和其相应的值。

您可以利用列表拆包(使用*)直接将排序后的数据传递给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() 函数按照元组中的项目顺序对元组进行排序,因此您不需要指定 key 函数,因为由 dict.item() 返回的元组已经以键值开头。


-1
更简单的方法:
plt.plot(list(dict.keys()), list(dict.values()))

1
那是插入顺序(现在)而不是关键顺序。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接