[英]Matplotlib-How do I plot a graph where the x values are the frequency of each y value?
If I'm trying to plot a graph of the number of people born in each month, and I have a list like: 如果我试图绘制每个月出生人数的图表,并且我有一个列表,例如:
[ {"bob": "January"},{"Peter":"February"},{"Mary":"March"}, {"John":"March"}, {"Sully": "March"}, {"Kai":"April"} ,{"Jerry": "February"}, {"Polly":"may"}, {"Nina": "June"}, {"Mic": "July"}, {"Paul": "August"}, {"Ferry": "January"}]
What is the best way to plot a graph with the months on the x axis and the number of people who are born in that month on the y axis? 在x轴上以月为单位,在y轴上以该月的出生人数绘制图表的最佳方法是什么? I have the y values which are the months, but I'm having trouble with the x values.
我的y值是月份,但x值有问题。 Do I have to go through the list and calculate the frequency of each month first?
我是否必须仔细查看清单并首先计算每个月的频率? I will be working with a much bigger list with more than a thousand items and need a solution that is efficient.
我将处理一个更大的列表,其中包含一千多个项目,并且需要一个有效的解决方案。
You can use ChainMap
to first flatten your list of dictionaries and then apply Counter
module to get the frequency of names for each month. 您可以使用
ChainMap
首先展平字典列表,然后应用Counter
模块获取每个月的名字出现频率。 Then you can extract the month names and the corresponding frequencies and plot them using a bar chart. 然后,您可以提取月份名称和相应的频率,并使用条形图进行绘制。 Below is a sample answer using your provided data.
以下是使用您提供的数据的示例答案。 If you want to sort the month names on the x-axis, you can use the answer provided here .
如果要在x轴上对月份名称进行排序,可以使用此处提供的答案。
from collections import Counter, ChainMap
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(8, 6))
dictionary = [{"bob": "January"},{"Peter":"February"},{"Mary":"March"}, {"John":"March"},
{"Sully": "March"}, {"Kai":"April"} ,{"Jerry": "February"}, {"Polly":"may"},
{"Nina": "June"}, {"Mic": "July"}, {"Paul": "August"}, {"Ferry": "January"}]
dict_flat = ChainMap(*dictionary)
frequency = Counter(dict_flat.values()).most_common()
x, y = zip(*frequency)
plt.bar(x, y, width=0.5)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.