按键值的顺序绘制python dict [英] Plotting a python dict in order of key values

查看:55
本文介绍了按键值的顺序绘制python dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 Python 字典:

输入[1]:dict_concentrationOut [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 连接了错误的点(附上图).我怎样才能让它按键值的顺序连接线?

解决方案

Python字典是无序的.如果您要订购字典,请使用

I have a python dictionary that looks like this:

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?

解决方案

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

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


Here is the result.

这篇关于按键值的顺序绘制python dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆