Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

python - Plotting a dictionary with multiple values per key

I have a dictionary that looks like this:

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

For a few hundred keys, I'd like to plot them with the key as y for its set of x values, I tried this bit of code which gives the error underneath:

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

I'm at a bit of a loss on how to proceed so any help would be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to construct your list of Xs and Ys manually:

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

resulting: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...