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?
dict1_sorted = {k: v for k, v in sorted(dict1.items(), key=lambda item: item[1])}
The sort routines are guaranteed to use __lt__() when making comparisons between two objects
- if your key objects support less-than comparison you can sortdict1.items()
anddict2.items()
to ensure order.