diff --git a/flaskapp/routes.py b/flaskapp/routes.py index ac7f7f5f0..c7555dda2 100644 --- a/flaskapp/routes.py +++ b/flaskapp/routes.py @@ -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 @@ -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/') +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) diff --git a/flaskapp/templates/chart1.html b/flaskapp/templates/chart1.html new file mode 100644 index 000000000..f4fba533d --- /dev/null +++ b/flaskapp/templates/chart1.html @@ -0,0 +1,2 @@ +

Chart 1: Average Turnout by Region

+ diff --git a/flaskapp/templates/chart2.html b/flaskapp/templates/chart2.html new file mode 100644 index 000000000..2860854dc --- /dev/null +++ b/flaskapp/templates/chart2.html @@ -0,0 +1,2 @@ +

Chart 2: Average Vote Share by Party

+ diff --git a/instance/site.db b/instance/site.db index 1f77ee429..175b20483 100644 Binary files a/instance/site.db and b/instance/site.db differ