Flask 10 - Graphs with plotly
Why plotly, fetching time series data, adding graphs with plotly, update the route
Staring at a bunch of numbers in a text-based weather forecast can feel dull, and boring af. A line graph, can instantly show you how temperatures are going to rise and fall throughout the day.
We’re going to improve our Flask app by adding a dynamic line graph using Plotly. This graph will take hourly temperature data for any city the user searches for and turn it into a clear, interactive visualization.
1 - Why Plotly
Plotly is a great for creating interactive, good-looking graphs that make complex data easy to understand.
Here’s why it’s solid for visualizing weather trends in our Flask app:
Interactive Features: Hover over data points to see exact values, zoom in on specific hours, or even download the graph.
Easy Integration: Plotly works beautifully with Python and Flask. In just a few lines of code, you can whip up clean, professional charts.
Dynamic Updates: If you want to see the weather for a different city, the graph updates instantly based on user input.
Customizable: You can control everything about the graph, and make it as customizable as you like.
Let’s process the data, and use plotly to make a graph with it.
2 - Fetching Time series data
Before we can visualize anything, we need detailed hourly weather data. OpenWeatherMap provides a forecast API endpoint that delivers weather predictions in three-hour intervals. Let’s modify the get_weather function to process this data.
def get_weather(query):
api_url = f'http://api.openweathermap.org/data/2.5/forecast?q={query}&units=metric&appid=cb932829eacb6a0e9ee4f38bfbf112ed'
try:
with urllib.request.urlopen(api_url) as response:
data = response.read()
parsed = json.loads(data)
forecast = {
"times": [item['dt_txt'] for item in parsed['list'][:8]], # First 8 intervals (~24 hours)
"temperatures": [item['main']['temp'] for item in parsed['list'][:8]]
}
current_weather = {
"description": parsed['list'][0]['weather'][0]['description'],
"temperature": parsed['list'][0]['main']['temp'],
"city": parsed['city']['name'],
"country": parsed['city']['country']
}
return forecast, current_weather
except Exception as e:
print(f"Error fetching weather data: {e}")
return None, None
Here’s a quick summary of what’s going on:
API URL
We dynamically create the API URL using the user’s search query.
The units=metric parameter ensures temperatures are returned in Celsius.
Fetching the API Response
We use urllib.request.urlopen to send an HTTP GET request to the API.
The response is read as raw data and then parsed into a Python dictionary using json.loads().
Extracting Hourly Data
We retrieve the first 8 data points (covering ~24 hours) for the forecast.
Each data point includes:
dt_txt: The timestamp for the forecast (e.g., "2024-12-16 06:00:00").
temp: The predicted temperature at that time.
Current Weather
The first entry in the forecast list provides the current weather details (temperature, description, city, and country).
Returning Data
The function returns two dictionaries:
forecast: For hourly data.
current_weather: For the current weather snapshot.
Here’s a quick sample of the Toronto output:
3 - Adding graphs with plotly
To include Plotly in our app, we’ll first add it to the HTML template.
Step 1: Include plotly in your template
Add the following lines to your home.html file:
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<h2>Temperature Throughout the Day</h2>
<div id="weatherGraph"></div>
Here’s a quick summary of the above:
Plotly Library Script:
The <script> tag includes the Plotly library, which is hosted on a Content Delivery Network.
Keep reading with a 7-day free trial
Subscribe to Data Science & Machine Learning 101 to keep reading this post and get 7 days of free access to the full post archives.