繁体   English   中英

绘制每个键具有多个值的字典

[英]Plotting a dictionary with multiple values per key

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

1: ['4026', '4024', '1940', '2912', '2916], 2: ['3139', '2464'], 3:['212']...

对于几百个键,我想用键作为y的x值集来绘制它们,我尝试了这段代码,它给出了下面的错误:

for rank, structs in b.iteritems():
    y = b.keys()
    x = b.values()
    ax.plot(x, y, 'ro')
    plt.show()

ValueError: setting an array element with a sequence

我对如何继续有点失落所以任何帮助将不胜感激!

您需要手动构建X和Y列表:

In [258]: b={1: ['4026', '4024', '1940', '2912', '2916'], 2: ['3139', '2464'], 3:['212']}

In [259]: xs, ys=zip(*((int(x), k) for k in b for x in b[k]))

In [260]: xs, ys
Out[260]: ((4026, 4024, 1940, 2912, 2916, 3139, 2464, 212), (1, 1, 1, 1, 1, 2, 2, 3))

In [261]: plt.plot(xs, ys, 'ro')
     ...: plt.show()

导致: 在此输入图像描述

1)重复你的x值

plot需要一个x值列表和一个y值列表,这些值必须具有相同的长度。 这就是为什么你必须多次重复rank值。 itertools.repeat()可以为你做到这一点。

2)改变你的迭代器

iteritems()已经返回一个元组(key,value) 您不必使用keys()items()

这是代码:

import itertools
for rank, structs in b.iteritems():
    x = list(itertools.repeat(rank, len(structs)))
    plt.plot(x,structs,'ro')

3)结合图

使用您的代码,您将在字典中为每个项目生成一个绘图。 我想你宁愿在一张图中绘制它们。 如果是这样,请按以下方式更改代码:

import itertools
x = []
y = []
for rank, structs in b.iteritems():
    x.extend(list(itertools.repeat(rank, len(structs))))
    y.extend(structs)
plt.plot(x,y,'ro')

4)例子

以下是使用您的数据的示例:

import itertools
import matplotlib.pyplot as plt
d = {1: ['4026', '4024', '1940', '2912', '2916'], 2: ['3139', '2464'], 3:['212']}
x= []
y= []
for k, v in d.iteritems():
    x.extend(list(itertools.repeat(k, len(v))))
    y.extend(v)
plt.xlim(0,5)
plt.plot(x,y,'ro')

在此输入图像描述

这是因为您的数据条目不匹配。

目前你有

1: ['4026', '4024', '1940', '2912', '2916']
2: ['3139', '2464'],
...

于是

x = [1,2,...]
y = [['4026', '4024', '1940', '2912', '2916'],['3139', '2464'],...

当你真的需要的时候

x = [1, 1, 1, 1, 1, 2, 2, ...]
y = ['4026', '4024', '1940', '2912', '2916', '3139', '2464',...]

尝试

for rank, structs in b.iteritems():
    # This matches each value for a given key with the appropriate # of copies of the 
    # value and flattens the list
    # Produces x = [1, 1, 1, 1, 1, 2, 2, ...]
    x = [key for (key,values) in b.items() for _ in xrange(len(values))]

    # Flatten keys list
    # Produces y = ['4026', '4024', '1940', '2912', '2916, '3139', '2464',...]
    y = [val for subl in b.values() for val in subl]

    ax.plot(x, y, 'ro')
    plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM