Matplotlib-How do I plot a graph where the x values are the frequency of each y value?

Viewed 117

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? I have the y values which are the months, but I'm having trouble with the x values. 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.

1 Answers

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. 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.

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

enter image description here

Related