Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions flaskapp/routes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
from flask import render_template, flash, redirect, url_for, request
from flaskapp import app, db
from flaskapp.models import BlogPost, IpView, Day
from flaskapp.models import UkData
from flaskapp.forms import PostForm
import datetime
import matplotlib
matplotlib.use('Agg') #Use non-GUI backend
import matplotlib.pyplot as plt
import io
import base64


import pandas as pd
import json
Expand Down Expand Up @@ -71,3 +78,57 @@ def before_request_func():
db.session.add(ip_view) # insert into the ip_view table

db.session.commit() # commit all the changes to the database

@app.route('/chart1')
def chart1():
data = UkData.query.all()
df = pd.DataFrame([d.__dict__ for d in data])

df['region'] = df['region'].str.strip()
df = df[~df['region'].isin(['Wales', 'Scotland'])]

if df.empty:
return "No English regions found in the data."

#Example chart: Voter turnout per region
turnout_by_region = df.groupby('region')['Turnout19'].mean()

fig, ax = plt.subplots()
turnout_by_region.plot(kind = 'bar', ax = ax)
ax.set_title("Average 2019 Turnout in English Regions")
ax.set_ylabel("Turnout (%)")

fig.tight_layout() #fix axis cropping

img = io.BytesIO()
fig.savefig(img, format = 'png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()

return render_template('chart1.html', plot_url = plot_url)

@app.route('/chart2')
@app.route('/chart2/<country>')
def chart2(country = None):
data = UkData.query.all()
df = pd.DataFrame([d.__dict__ for d in data])

if country:
df = df[df['region'].str.lower() == country.lower()]

party_votes = df[['ConVote19', 'LabVote19', 'LDVote19']].mean()
party_votes.index = ['Conservative', 'Labour', 'Liberal Democrats']

fig, ax = plt.subplots()
party_votes.plot(kind='pie', ax = ax, autopct = '%1.1f%%')
ax.set_title(f"Average Vote Share{' in ' + country.title() if country else ''}")
ax.set_ylabel('')

fig.tight_layout() #fix axis cropping

img = io.BytesIO()
fig.savefig(img, format = 'png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()

return render_template('chart2.html', plot_url = plot_url)
2 changes: 2 additions & 0 deletions flaskapp/templates/chart1.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h2>Chart 1: Average Turnout by Region</h2>
<img src="data:image/png;base64,{{ plot_url }}" />
2 changes: 2 additions & 0 deletions flaskapp/templates/chart2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h2>Chart 2: Average Vote Share by Party</h2>
<img src="data:image/png;base64,{{ plot_url }}" />
Binary file modified instance/site.db
Binary file not shown.