w3resource

Real-Time Data Visualization Dashboard with Plotly and Dash

Write a Python program to build a real-time data visualization dashboard using Plotly and Dash.

The task involves creating a real-time data visualization dashboard using Plotly and Dash modules. This dashboard will dynamically update and display data, allowing users to visualize changes as they occur in real-time. It should leverage Plotly for creating interactive and visually appealing graphs, and Dash for building the web-based interface and handling real-time data updates. The aim is to provide a tool that can effectively monitor and display data trends continuously.

Sample Solution:

Python Code :

# Import necessary libraries
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import random

# Function to generate random data
def generate_data():
    # Create a dictionary with timestamps and random values
    return {
        'timestamp': pd.date_range(start='2022-01-01', periods=100, freq='H'),
        'value': [random.randint(0, 100) for _ in range(100)]
    }

# Create a Dash app instance
app = dash.Dash(__name__)

# Define the layout of the app
app.layout = html.Div([
    # Add a header to the dashboard
    html.H1("Real-Time Data Visualization Dashboard"),
    # Add a Graph component to display the plot
    dcc.Graph(id='real-time-plot'),
    # Add an Interval component to update the plot at regular intervals
    dcc.Interval(
        id='interval-component',
        interval=1000,  # Update every 1000 milliseconds (1 second)
        n_intervals=0  # Initial number of intervals
    )
])

# Define a callback function to update the plot with new data
@app.callback(
    Output('real-time-plot', 'figure'),  # Output is the figure of the Graph component
    Input('interval-component', 'n_intervals')  # Input is the number of intervals
)
def update_plot(n):
    # Generate new data
    data = generate_data()
    # Convert the data into a DataFrame
    df = pd.DataFrame(data)
    
    # Create a line plot using Plotly Express
    fig = px.line(df, x='timestamp', y='value', title='Real-Time Data')
    
    # Return the plot
    return fig

# Run the app server
if __name__ == '__main__':
    # Start the Dash app with debug mode enabled
    app.run_server(debug=True)

Output:

Address: 'http://127.0.0.1:8050'
Real time Data Visualization Dashboard.png

Explanation:

  • Import Libraries: Necessary libraries such as Dash for the web application, Plotly Express for data visualization, Pandas for data manipulation, and Random for generating random data are imported.
  • Generate Random Data: The "generate_data()" function creates a dictionary with timestamps and random values. This data simulates the real-time data to be visualized.
  • Create Dash App: An instance of the Dash app is created, which will serve as the web application framework.
  • App Layout: The layout of the app is defined using Dash HTML components. It includes:
  • A header (H1) for the dashboard title.
  • A Graph component to display the plot.
  • An Interval component that triggers updates every second.
  • Callback Function: The "update_plot()" function is defined as a callback that updates the plot:
  • It generates new random data.
  • Converts the data into a DataFrame.
  • Creates a line plot using Plotly Express.
  • Returns the updated plot.
  • Run the App: The app server is started with app.run_server(debug=True), allowing the dashboard to be accessed in a web browser with real-time updates enabled.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Genetic Algorithm for Optimization.
Next: Python Library for Polynomial Arithmetic

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/advanced/build-a-real-time-data-visualization-dashboard-with-plotly-and-dash.php