INF201/uke1/5:diagram.py

33 lines
1.1 KiB
Python

import matplotlib.pyplot as plt
import numpy as np
def main():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
n = len(res.keys())
x = 0.5 + np.arange(n)
y = res.values()
fig, ax = plt.subplots()
ax.bar(res.keys(), y, edgecolor="white", linewidth=0.7)
ax.set(xlabel=head[0], ylabel=head[1])
plt.xticks(rotation = 90)
plt.show()
if __name__ == "__main__":
main()