简体   繁体   中英

Plotting multiple variables in matplotlib python

I'm trying to plot a bar graph, and I have multiple lists for xaxisn (n from 1 to 5) and yaxisn (1 to 5). The values in each respective xaxisn were originally mapped to the values in yaxisn in a dictionary, and they are the same from 1 to 5 but in different order. For example

dict1 = {'a': 80, 'c': 30, 'e': 52, 'b': 12, 'd': 67}
dict2 = {'c': 47, 'a': 73, 'e': 32, 'd': 35, 'b': 40}

So I created a list containing all the nominal values for x and tried to plot everything together with

xaxis = ['a', 'b', 'c', 'd', 'e']
yaxis1 = dict1.values()
xaxis1 = dict1.keys()
yaxis2 = dict2.values()
xaxis2 = dict2.keys()
plt.bar(xaxis1,yaxis1)
plt.bar(xaxis2,yaxis2)
plt.xticks(range(len(xaxis)),xaxis)

but I've noticed that despite being mapped together, the y values in the graph aren't aligned to the right x. So instead of showing, in order the frequencies for xaxis , they keep the same order as in the dictionary. I have tried to change the last line of code into

plt.xticks(range(len(xaxis)),xaxis1)
plt.xticks(range(len(xaxis)),xaxis2)

but again, with multiple variables, one overwrites the previous one. Do I need to order all the dictionaries the same way to plot them, or is there another way to do it without having to redo all my codes?

You can ensure that the order for the two y axes are the same by using the keys of one dict to extract the values from both. Here is one way to do it.

import operator

dict1 = {'a': 80, 'c': 30, 'e': 52, 'b': 12, 'd': 67}
dict2 = {'c': 47, 'a': 73, 'e': 32, 'd': 35, 'b': 40}

xs = dict1.keys()
f = operator.itemgetter(*xs)
y1 = f(dict1)
y2 = f(dict2)

>>> xs
dict_keys(['a', 'c', 'e', 'b', 'd'])
>>> y1
(80, 30, 52, 12, 67)
>>> y2
(73, 47, 32, 40, 35)
>>>

Then use xs for all the plotting.

plt.bar(xs,y1)
plt.bar(xs,y2)
plt.xticks(range(len(xs)),xs)
plt.show()
plt.close()

operator.itemgetter will get each item it is instantiated with in the order they were given. Similar to these list comprehensions.

>>> [dict1[k] for k in xs]
[80, 30, 52, 12, 67]
>>> [dict2[k] for k in xs]
[73, 47, 32, 40, 35]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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