Skip to content

Instantly share code, notes, and snippets.

@niftycode
Last active December 29, 2019 10:47
Show Gist options
  • Save niftycode/8123667ccba606e2bddcd9e48568a67b to your computer and use it in GitHub Desktop.
Save niftycode/8123667ccba606e2bddcd9e48568a67b to your computer and use it in GitHub Desktop.
UK General Election 2019 Bar Chart
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UK General Election 2019
Version: 1.1
Python 3.8
Date created: 28.12.2019
"""
import requests
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
URL = "https://xern-statistic.de/api/election"
def fetch_json_data(json_url):
# Connect to the server
try:
response = requests.get(json_url)
except OSError as e:
print("Error: {0}".format(e))
return None
# Check if the status code is OK
# and receive data
if response.status_code == 200:
print("Status 200, OK")
return response.json()
else:
print("JSON data request not successfull!")
return None
json_data = fetch_json_data(URL)
pprint(json_data)
parties = list(json_data.keys())
print(parties)
seats = list(json_data.values())
print(seats)
fig, ax = plt.subplots()
y_pos = np.arange(len(parties))
color = ['#3D81CB', '#B90E00', '#F8E900', '#E09000', '#7E0700', '#306A18', '#528F2B', '#55B728', '#52BDD0', '#BDBDBD', '#767676']
plt.title('UK General Election 2019')
plt.ylabel('Seats')
plt.xlabel('Parties')
plt.bar(y_pos, seats, align='center', alpha=0.6, color=color)
ax.set_xticks(range(len(parties)))
ax.set_xticklabels(parties, rotation='vertical')
c_rects = plt.bar(y_pos, seats, align='center', alpha=0.6, color=color)
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., height + 1.5,
int(height),
ha='center', va='bottom')
autolabel(c_rects)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment