简体   繁体   English

在matplotlib python中绘制多个变量

[英]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).我正在尝试绘制条形图,并且我有多个 xaxisn(n 从 1 到 5)和 yaxisn(1 到 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.每个xaxisn 中的值最初映射到字典中yaxisn 中的值,它们从1 到5 相同,但顺序不同。 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所以我创建了一个包含 x 的所有标称值的列表,并尝试将所有内容与

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.但我注意到尽管被映射在一起,图中的 y 值并未与正确的 x 对齐。 So instead of showing, in order the frequencies for xaxis , they keep the same order as in the dictionary.因此,不是按顺序显示xaxis的频率, xaxis保持与字典中相同的顺序。 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.您可以通过使用一个 dict 的键从两者中提取值来确保两个 y 轴的顺序相同。 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.然后使用xs进行所有绘图。

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. operator.itemgetter将按照给定的顺序获取实例化的每个项目。 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]
>>> 

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

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