The Wayback Machine - https://web.archive.org/web/20240916041404/https://www.geeksforgeeks.org/plot-live-graphs-using-python-dash-and-plotly/
Open In App

Plot Live Graphs using Python Dash and Plotly

Last Updated : 16 Jul, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload each time the data is updated. This can be done using a feature called “hot reloading”, not to be confused with “live reloading”. Live reloading reloads or refreshes the entire app when the data is updated, while hot reloading only refreshes the data that was updated without changing the state of the app. Dash automatically includes hot-reloading making it the best choice for this kind of visualization. 

Now, let’s build a dashboard that generates random data, appends it onto a buffer at regular intervals and visualizes the same. 

Install Dash module and Plotly modules. 

pip install dash
pip install plotly

First, let’s import all the required modules and dependencies. Import Output and Input for callbacks, dash_core_components for graphs and other basic components offered by Dash. Import dash_html_components offers basic HTML components. Also, import dash and plotly. Import the graph_objs from plotly for graph features. Import deque(Doubly Ended Queue) from collections.

import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque

Let’s initialize two deques for X and Y components of the graph. Append single data to it, this will be our first points on the graph. 

X = deque(maxlen = 20)
X.append(1)

Y = deque(maxlen = 20)
Y.append(1)

Initialize the dash app.

app = dash.Dash(__name__)

Now let’s specify the layout of the dashboard that we want to build. It is important to note that there is no need to write HTML pages for the layout and we can use dash’s HTML components to make simple layouts. Let’s build a simple layout with just a graph component. In the code below, let’s set animate to True, this will easily handle scroll animations for the graph which would look better than an abrupt change in the values after updating. Let’s assign an id to the graph component. We have another component named Interval, which has properties like id which specifies a unique ID for this component. The property interval specifies the time elapsed between two updations of data. n_interval refers to the number of intervals completed from the start of the server.

app.layout = html.Div(
    [    
        dcc.Graph(id = 'live-graph',
                  animate = True),
        dcc.Interval(
            id = 'graph-update',
            interval = 1000,
            n_intervals = 0
        ),
    ]
)

Now let’s call the callback decorators

@app.callback(
    Output('live-graph', 'figure'),
    [ Input('graph-update', 'n_intervals') ]
)

Now let’s make the update_graph method which takes in n_intervals as parameter. Let’s update X values sequentially, i.e., from 1 to 2 to 3 and so on. Let’s update Y values to random values. Now let’s make a new data variable and assign it to a plotly graph. Plotly graphs, by default, requires you to set X and Y values with a list. Let’s specify the mode to “lines+markers” which essentially means that Plotly is going to plot markers first and then draw lines to it.

def update_graph_scatter(n):
    X.append(X[-1]+1)
    Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1))

    data = plotly.graph_objs.Scatter(
            x=list(X),
            y=list(Y),
            name='Scatter',
            mode= 'lines+markers'
    )

    return {'data': [data],
            'layout' : go.Layout(xaxis=dict(
                    range=[min(X),max(X)]),yaxis = 
                    dict(range = [min(Y),max(Y)]),
                    )}

Finally, run the server.

if __name__ == '__main__':
    app.run_server()

Complete Code:

Python3




import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque
  
X = deque(maxlen = 20)
X.append(1)
  
Y = deque(maxlen = 20)
Y.append(1)
  
app = dash.Dash(__name__)
  
app.layout = html.Div(
    [
        dcc.Graph(id = 'live-graph', animate = True),
        dcc.Interval(
            id = 'graph-update',
            interval = 1000,
            n_intervals = 0
        ),
    ]
)
  
@app.callback(
    Output('live-graph', 'figure'),
    [ Input('graph-update', 'n_intervals') ]
)
  
def update_graph_scatter(n):
    X.append(X[-1]+1)
    Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1))
  
    data = plotly.graph_objs.Scatter(
            x=list(X),
            y=list(Y),
            name='Scatter',
            mode= 'lines+markers'
    )
  
    return {'data': [data],
            'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),yaxis = dict(range = [min(Y),max(Y)]),)}
  
if __name__ == '__main__':
    app.run_server()


Open the browser and run the app on the local host and port 8050

http://localhost:8050/

Output:

This is how dash can be used for live graph visualizations. In this article, we have used it with random values generated by the computer. However, the same can be done with data pulled from APIs or a database. 



Previous Article
Next Article

Similar Reads

Define Colors in a Figure Using Plotly Graph Objects and Plotly Express
Whether you use Plotly Graph Objects or Plotly Express, defining colors in your figures allows you to create visually appealing and informative visualizations. Plotly's flexibility in color customization helps you highlight important data points, differentiate categories, and make your charts more engaging in Python. Plotly Graph ObjectsPlotly Grap
3 min read
How to hide legend with Plotly Express and Plotly in Python?
In this article, we will learn How to hide legend with Plotly Express and Plotly. Here we will discuss two different methods for hiding legend in plotly and plotly express, using two different examples for each to make it more clear. Syntax: For legend: fig.update_traces(showlegend=False)fig.update(layout_showlegend=False) Example 1: In this exampl
2 min read
Plotly - How to show legend in single-trace scatterplot with plotly express?
In this article let's see how to show legend in single-trace scatterplot with plotly express. A 'trace' is the name given to each plot inside the chart. Generally in plotly legend is not visible for single trace scatter plots. Example: In the below, example packages and data are imported and a single trace scatter plot is plotted using px.scatter()
1 min read
Setting X Axis Range on Plotly Graphs
Plotly is a powerful graphing library that enables the creation of interactive and visually appealing plots in Python. One of the key features of Plotly is its ability to customize the axes of a graph, including setting the range of the x-axis. This article will provide a comprehensive guide on how to set the x-axis range in Plotly graphs, covering
4 min read
Introduction to Dash in Python
Dash is a Python framework for building analytical web applications. Dash helps in building responsive web dashboards that is good to look at and is very fast without the need to understand complex front-end frameworks or languages such as HTML, CSS, JavaScript. Let's build our first web dashboard using Dash. Installation and Imports Install the la
4 min read
Pie plot using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Pie Plot A pie chart is a circular analytical ch
3 min read
Box Plot using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Box Plot A box plot is a demographic representat
8 min read
How to Create Stacked area plot using Plotly in Python?
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Stacked Area plot A stacked area chart is the am
2 min read
3D scatter plot using Plotly in Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. 3D Scatter plot in Plotly A scatterplot can be u
3 min read
3D Scatter Plot using graph_objects Class in Plotly-Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Scatter plot using graph_objects class If a plot
2 min read
Sunburst Plot using Plotly in Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Sunburst Plot in Plotly Sunburst plot visualizes
4 min read
Parallel Coordinates Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. Parallel Coordinates Plot Parallel coordinates
2 min read
Carpet Contour Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Carpet Contour Plot A carpet contour plot is a
2 min read
Ternary contours Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Ternary contours in Plotly In plotly, ternary
3 min read
Scatter plot using Plotly in Python
Plotly Python is a library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. Plotly python is an interactive visualization library. Scatter PlotA scatter plot is a diagram w
5 min read
Violin plot using Plotly in Python
Violin Plot is a method to visualize the distribution of numerical data of different variables. It is similar to Box Plot but with a rotated plot on each side, giving more information about the density estimate on the y-axis. The density is mirrored and flipped over and the resulting shape is filled in, creating an image resembling a violin. The ad
4 min read
Box plot in Plotly using graph_objects class
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Box plot using graph objects class If Plotly Exp
4 min read
Scatter plot in Plotly using graph_objects class
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Scatter plot using graph_objects class Scatter p
3 min read
Sunburst Plot using graph_objects class in plotly
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Sunburst Plot using graph_objects class If Plotl
3 min read
How to plot on secondary Y-Axis with Plotly Express in Python?
Perquisites: Python Plotly In this article, we will learn how to plot on secondary y-Axis with plotly express. One of the most deceptively-powerful features of Plotly data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us t
3 min read
How to position legends inside a plot in Plotly-Python?
In this article, we will learn How to hide legend with Plotly Express and Plotly. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes. Example 1: In this example, we are positioning legends inside a plot with the help of method fig.update_layout(), by passing the position as x=0.3 and
2 min read
Python Plotly: How to prevent title from overlapping the plot?
The structure & representation of the data are an integral part of the data-driven decision-making process as well as the entire data science pathway. Data View is the process of presenting data in image and image format. Visual representation of data makes understanding complex concepts easier, and new patterns in data can be easily identified
3 min read
How to create Grouped box plot in Plotly?
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. What is a Grouped box plot? A grouped box plot i
2 min read
Querying Live running status and PNR of trains using Railway API in Python
Railway API is organized around GET Requests. One can use this JSON based API to get information from Indian Railways regarding Live Train Status, PNR Status, Train Schedule, Station Details, and other things. To use this API, one must need the API key, which can get from here Note: User need to create an account on railwayapi.com to use the APIs.
5 min read
Histogram using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Histogram in Plotly A histogram is a graph where
3 min read
How to make a basic Scatterplot using Python-Plotly?
Plotly is a graphing library for making high quality interactive graphs and charts. It is an open source library used for data visualization . This library can be used with three programming languages namely Python, R and Javascript. Using Plotly is very easy and you can make any type of graph using this library. It can generate Statistical charts,
2 min read
Treemap using Plotly in Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Treemap in Plotly Treemap in plotly.express is c
3 min read
Bar chart using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Bar Chart in Plotly Bar chart with plotly expre
2 min read
Bubble chart using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. Bubble Chart The bubble chart in Plotly is crea
3 min read
Bar chart using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. Bar Chart In a bar chart the data categories ar
4 min read