SoFunction
Updated on 2025-03-04

Python Bokeh implements real-time data visualization

Data visualization is an integral part of data analysis and scientific computing. It can visually display data and help us quickly discover patterns and trends. Bokeh is a powerful data visualization library in Python, especially good at creating interactive and real-time updated charts. This article will introduce how to use the Bokeh library for real-time data visualization through concise language and specific code examples.

1. Introduction to Bokeh

Bokeh provides a wealth of chart types and tools that support the creation of complex visual works and can be easily embedded into web pages. Its core features include:

  • Interactive chart: Users can interact with charts, such as scaling, panning, hovering to view data point information, etc.
  • Real-time update: Bokeh is able to update charts in real time, ideal for monitoring and real-time data analysis.
  • Rich chart types: including line charts, bar charts, scatter charts, heat charts, etc.
  • Easy to integrate: It can be seamlessly integrated with Jupyter Notebook, Flask and other frameworks.

2. Install Bokeh

Before you start, you need to make sure that the Bokeh library is installed. You can use the following command to install:

pip install bokeh

3. Create a simple Bokeh chart

Let's start by creating a simple line chart to understand the basic usage of Bokeh.

from  import figure, show, output_file
from  import output_notebook
import numpy as np
 
# Show Bokeh charts in Jupyter Notebookoutput_notebook()
 
# Create datax = (0, 10, 100)
y = (x)
 
# Create a chart objectp = figure(title="Simple Line Plot", x_axis_label='x', y_axis_label='sin(x)')
 
# Add data to the chart(x, y, line_width=2)
 
# Show chartsshow(p)

This code creates a simple line chart showing the change of the function sin(x) over the interval [0, 10]. In Jupyter Notebook, the output_notebook() function allows Bokeh charts to be displayed directly in the notebook.

4. Real-time update of charts

What makes Bokeh powerful is its ability to update charts in real time. This usually involves two main parts: updates to the data source and redrawing of the chart.

We can use ColumnDataSource as the data source and trigger the re-rendering of the chart when the data is updated through the callback function. Here is a simple example showing how to create a live updated line chart.

from  import figure, curdoc
from  import ColumnDataSource
from  import row
from  import push_session
from  import Server
import numpy as np
import time
import random
 
# Create a data sourcesource = ColumnDataSource(data=dict(x=[], y=[]))
 
# Create a chart objectp = figure(title="Real-time Line Plot", x_axis_label='Time', y_axis_label='Value', x_range=(0, 50))
('x', 'y', source=source, line_width=2)
 
# callback function for updating datadef update():
    new_data = {'x': ['x'] + [['x'][-1] + 1 if ['x'] else 0],
                'y': ['y'] + [(0, 10)]}
    (new_data, rollover=len(['x']) > 50)  # Keep up to 50 data points 
# Set callback function to call periodicallycurdoc().add_periodic_callback(update, 1000)  # Update every 1000 milliseconds (1 second) 
# If running in a Jupyter Notebook, use show() to display the chart# Otherwise, run with Bokeh server# show(row(p), notebook_handle=True) # Jupyter Notebook method 
#Use Bokeh server methodsession = push_session(curdoc())
try:
    server = Server({'/': curdoc()}, io_loop=, allow_websocket_origin=["*"])
    ()
    session.loop_until_closed()
except KeyboardInterrupt:
    pass
finally:
    ()
    ()

In this example, we create a ColumnDataSource as the data source and update the data periodically via the update function. The stream method is used to add new data to the data source, and the rollover parameter ensures that the number of data points in the data source does not exceed 50. We use the add_periodic_callback method to set the callback function to be called every 1000 milliseconds (1 second).

Note: If you run this code in a Jupyter Notebook, you may need to use show(row(p), notebook_handle=True) to display the chart. However, for real-time updates, the more common way is to use a Bokeh server. The above code example shows how to run a chart using a Bokeh server and configure it through push_session and Server classes.

5. Integrate into Flask applications

Bokeh can also integrate with web frameworks such as Flask to create complete web applications. Here is a simple example showing how to integrate Bokeh charts into Flask apps.

from flask import Flask, render_template_string
from  import figure
from  import components
from  import CDN
from  import ColumnDataSource
import numpy as np
 
app = Flask(__name__)
 
# Create Bokeh charts and data sourcessource = ColumnDataSource(data=dict(x=(0, 10, 100), y=((0, 10, 100))))
p = figure(title="Flask-integrated Bokeh Plot", x_axis_label='x', y_axis_label='sin(x)')
('x', 'y', source=source, line_width=2)
 
# Embed Bokeh chart into HTML templatescript, div = components(p, CDN)
 
# Define Flask routing and view functions@('/')
def index():
    html = render_template_string("""
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>Flask-integrated Bokeh Plot</title>
        {{ script|safe }}
      </head>
      <body>
        {{ div|safe }}
      </body>
    </html>
  """, script=script, div=div)
    return html
 
if __name__ == '__main__':
    (debug=True)

In this example, we first create a simple Bokeh chart and data source. We then use the components function to convert the chart into HTML script and div elements. Next, we define a Flask routing and view function that embeds the Bokeh chart into the HTML template and returns it to the client.

After running this Flask app, you can open http://127.0.0.1:5000/ in your browser to view the embedded Bokeh chart.

6. Things to note

Performance optimization: For real-time updates of large amounts of data, performance optimization may need to be considered, such as reducing the number of data points in the data source, using more efficient data structures, etc.

Security: When integrating Bokeh charts into web applications, be sure to pay attention to security issues, such as preventing cross-site scripting attacks (XSS).

Error handling: During the real-time data update process, various abnormal situations may be encountered (such as network interruption, data source exceptions, etc.), and error handling is required.

7. Summary

This article describes how to use Python's Bokeh library for real-time data visualization. We started with a simple line chart and gradually learned more about how to update charts in real time and how to integrate charts into medium-to-high-level usages in Flask apps.

The above is the detailed content of Python Bokeh real-time data visualization. For more information about Python Bokeh data visualization, please follow my other related articles!