Exploring Twitter API and Data Using Tweepy, Pandas and Matplotlib. — Part 2

from io import BytesIO
from flask import Flask, render_template, send_file, make_response
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from tweets_analyzer import analyze, plot_graphs
import matplotlib.pyplot as plt
app = Flask(__name__)

Showing Dataframes:

def index():
analysis_details = analyze()
fans_by_housemate, fans_by_location, followers_of_fans_by_hm = analysis_details
fans_by_location_table = fans_by_location.pivot_table(index='location', columns='housemate_name', values='count')
return render_template("index.html", fans_by_housemate_df=fans_by_housemate.to_html(),
followers_of_fans_by_hm_df=followers_of_fans_by_hm.to_html(), fans_by_location_df=fans_by_location_table.to_html())
<div class="dataframe">
<h2>Fans by Housemate Data Frame</h2>
{{ fans_by_housemate_df | safe }}
<a href="#fbh_bc">See Graph</a>
<div class="dataframe">
<h2>Average Number of Followers of Fans by Housemate Data Frame</h2>
{{ followers_of_fans_by_hm_df | safe }}
<a href="#fbh_bc">See Graph</a>
<div class="dataframe">
<h2>Fans of Housemates by Location</h2>
{{ fans_by_location_df | safe }}
<a href="#fbl_bc">See Graph</a>
Web page showing dataframes as tables

Showing Charts

def fans_by_hm_bar_chart():
figures = plot_graphs()
fig1 = figures[0]
canvas = FigureCanvas(fig1)
img = BytesIO()
return send_file(img, mimetype='image/png')
<div class="chart" id="fbh_bc">
<h2>Fans by Housemate Bar Chart</h2>
<img src="/fans_by_hm_bar_chart/" alt="Fans By Housemate Bar Chart">
def fans_by_location_bar_chart():
figures = plot_graphs()
fig2 = figures[1]
canvas = FigureCanvas(fig2)
img = BytesIO()
return send_file(img, mimetype='image/png')
if __name__ == "__main__":
<div class="chart" id="fbl_bc">
<h2>Fans of Housemates by Location</h2>
<img src="/fans_by_location_bar_chart/" alt="Fans of Housemates by Location Bar Chart">
Web page with Bar Charts


  1. Passing dataframe to a web page.
  2. Passing Plots to a web page.
  3. Flask
  4. Flask Documentation
  5. Bytes IO



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store