Real-Time Weather Dashboard with Dash + Plotly

1. Introduction to Dash

  • What is Dash?

    • Dash is a Python framework for building web applications, particularly designed for creating interactive visualizations with Plotly.

    • It allows data scientists and developers to create fully interactive, web-based dashboards with minimal front-end development knowledge.

  • Relation to Plotly:

    • Plotly provides powerful, high-quality graphing capabilities, and Dash integrates these into web applications. Dash leverages Plotly’s charts to build interactive and visually rich dashboards.

2. History and Connection with Plotly

  • Background of Plotly:

    • Plotly is a company that provides a library for creating interactive data visualizations, widely used by data scientists and analysts.

    • Over time, Plotly has expanded to offer various chart types, including scientific graphs, financial charts, and geospatial data maps.

  • Dash's Evolution:

    • Dash was created by Plotly to allow Python users to build interactive dashboards for visualizing their data without having to learn web development tools like HTML, CSS, or JavaScript.

    • Dash simplifies the creation of complex data visualizations into interactive web apps.


3. Capabilities and Advantages of Dash

  • Interactive Features:

    • Dash allows users to interact with data in real time. Users can change dropdown selections, use sliders, and interact with charts to explore different views of data.

    • Dash supports dynamic charts, updating in real time based on the user’s inputs.

  • User-Friendly for Data Scientists:

    • Data scientists familiar with Python can build dashboards without needing to delve into complex web technologies like JavaScript and HTML.

    • Dash supports a variety of Python libraries, including Pandas, NumPy, and Plotly, making it an excellent tool for data analysis and visualization.

  • Scalability:

    • Dash can handle large datasets and update visualizations quickly, making it ideal for building real-time dashboards that pull data from live APIs or databases.

4. Use Case: Weather Dashboard

  • Visualization of Weather Data:

    • In this example, we will create a real-time weather dashboard that allows users to visualize the weather data of any city.

    • The data will come from an open weather API (like OpenWeatherMap or WeatherAPI), which provides information such as temperature, humidity, and weather conditions.

  • Features of the Weather Dashboard:

    • Users can input the name of a city and see real-time data such as the temperature, humidity, and weather description.

    • Interactive charts, such as temperature vs. time, allow users to visualize temperature fluctuations throughout the day.


5. Full Code Example: Callbacks and Layout

  • Creating the Layout:

    • We will use Dash's layout components to create a user-friendly interface, including a text input for the city name, a dropdown for temperature units (Celsius or Fahrenheit), and a graph to display weather data.
  • Callbacks to Update Data:

    • When the user submits a city, the dashboard will fetch weather data from the OpenWeatherMap API and display it in the graph and text fields.

Here's the Python code for the Weather Dashboard:

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import requests

# Initialize the Dash app
app = dash.Dash(__name__)
server = app.server  # Necesario para despliegue en Render/Heroku

# Layout of the app
app.layout = html.Div([
    html.H1("Weather Dashboard"),

    # Input for city name
    dcc.Input(id='city-input', type='text', placeholder='Enter city name', debounce=True),

    # Dropdown to select temperature unit
    dcc.Dropdown(
        id='unit-dropdown',
        options=[{'label': 'Celsius', 'value': 'metric'}, {'label': 'Fahrenheit', 'value': 'imperial'}],
        value='metric',  # Default is Celsius
        style={'width': '40%'}
    ),

    # Graph for displaying temperature
    dcc.Graph(id='temperature-graph'),

    # Text output for weather description
    html.Div(id='weather-description'),
])

# API key for OpenWeatherMap
API_KEY = "81c5bcdcc612d7e091edf3107ec20359"

# Callback to update weather data based on city input and selected unit
@app.callback(
    [Output('temperature-graph', 'figure'),
     Output('weather-description', 'children')],
    [Input('city-input', 'value'),
     Input('unit-dropdown', 'value')]
)
def update_weather(city, unit):
    if not city:
        return px.line(), "Enter a city name to get weather data."

    city_name = f"{city},PE"  # Add ',PE' for Peru

    url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&units={unit}&appid={API_KEY}"
    response = requests.get(url)
    data = response.json()

    print(data)  # For debugging

    if data.get('cod') != 200:
        return px.line(), f"Error: {data.get('message', 'City not found. Please try again.')}"

    temperature = data['main']['temp']
    description = data['weather'][0]['description']

    fig = px.bar(
        x=[city],
        y=[temperature],
        labels={'x': 'City', 'y': 'Temperature'},
        title=f"Current Temperature in {city}"
    )

    return fig, f"Weather Description: {description.capitalize()}"

if __name__ == '__main__':
    app.run(debug=True)

https://github.com/jf2021070309/Weather-Dashboard-with-Dash-Plotly

6. Deployment on Render

To deploy our Dash application, we used Render as the hosting platform. We created a Procfile with the line web: gunicorn app:app.server to define the startup command and listed all necessary dependencies (dash, plotly, requests, gunicorn) in the requirements.txt file. After pushing the repository to GitHub, we connected the GitHub account to Render, selected the repository, and Render automatically installed the dependencies and deployed the app.

https://weather-dashboard-with-dash-plotly.onrender.com

https://youtu.be/ykR6jFCfRok?si=iV-y4QIWxCGiWYeU

7. Conclusion

Dash has become a powerful and accessible tool for data scientists and developers to build interactive web applications without advanced front-end knowledge. By integrating directly with Plotly, Dash enables high-quality, dynamic visualizations using only Python. In the Weather Dashboard project, we demonstrated how to connect real-time data from OpenWeatherMap with interactive Dash components to create a user-friendly and visually appealing experience. Furthermore, platforms like Render simplify deployment, making it easy to scale projects from local prototypes to fully functional web apps. In summary, Dash offers an efficient solution for turning data into powerful, shareable visual tools.

11
Subscribe to my newsletter

Read articles from JAIME ELIAS FLORES QUISPE directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

JAIME ELIAS FLORES QUISPE
JAIME ELIAS FLORES QUISPE