Embedding Bokeh into HTML with PyScript and Custom JavaScript Callbacks

Embedding Bokeh into HTML with PyScript and Custom JavaScript Callbacks

This article explores the process of embedding Bokeh plots into an HTML page using PyScript, a modern web framework for Python. It covers the creation of a CSS-based resize handle, the implementation of custom JavaScript callbacks to interact with Bokeh plots, and how to pass data back to a specific div on the HTML page.

In this article, we will delve into the integration of Bokeh plots into HTML pages using PyScript, a powerful and easy-to-use framework for Python. We will explore how to create a custom CSS-based resize handle, implement custom JavaScript callbacks to manipulate Bokeh plots, and ensure that these interactions update data displayed in specific divs on the HTML page.

Step 1: Setting Up the Environment

First, ensure you have the necessary libraries installed. You'll need Bokeh, PyScript, and other supporting packages. Here's how you can install them:

bash 复制代码
pip install bokeh pyscript
Step 2: Creating the Basic HTML Structure

Let's start by setting up a basic HTML structure where we will embed our Bokeh plot.

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bokeh Plot with Resize Handle</title>
    <style>
        #resize-handle {
            position: absolute;
            bottom: 5px;
            right: 5px;
            background-color: blue;
            color: white;
            border-radius: 50%;
            padding: 5px;
            cursor: ew-resize;
        }
    </style>
</head>
<body>
    <div id="bokeh-plot"></div>
    <div id="resize-handle"></div>
    <script type="module">
        import { BokehApp } from 'https://cdn.pyscript.net/alpha?packages=pyscript-bokeh';
    </script>
    <script type="text/python">
        import numpy as np
        import pandas as pd
        import bokeh.plotting as bp
        import bokeh.models as bm

        def generate_data():
            x = np.linspace(0, 10, 100)
            y = np.sin(x)
            df = pd.DataFrame({'x': x, 'y': y})
            return df

        def update_plot(df):
            p = bp.figure(title='Sine Wave', x_axis_label='X', y_axis_label='Y')
            p.line(df['x'], df['y'], line_width=2)
            return p

        df = generate_data()
        p = update_plot(df)

        app = BokehApp(p)

        @app.callback
        def resize_plot():
            # Logic to resize the plot here
            pass

        app.run_bokehjs()

    </script>
</body>
</html>
Step 3: Adding a Custom Resize Handle

Next, let's add a custom CSS-based resize handle to allow users to adjust the size of the Bokeh plot.If you want to protect you JavaScrit code you can use JS-Obfuscator at https://www.js-obfuscator.com

html 复制代码
<div id="resize-handle" onclick="handleResize()"></div>

<script>
function handleResize(event) {
    const handle = document.getElementById('resize-handle');
    const plotContainer = document.getElementById('bokeh-plot');
    const handleWidth = handle.offsetWidth;
    const handleHeight = handle.offsetHeight;

    const plotWidth = plotContainer.offsetWidth;
    const plotHeight = plotContainer.offsetHeight;

    // Logic to calculate new plot dimensions based on handle position
    // For simplicity, we're just adjusting the width here.
    const newPlotWidth = plotWidth + (handleWidth / 2);

    // Update the Bokeh plot with the new width
    const new_plot = bp.figure(width=newPlotWidth, height=plotHeight);
    new_plot.line(df['x'], df['y'], line_width=2);
    plotContainer.innerHTML = ''; // Clear the existing plot
    plotContainer.appendChild(new_plot.html());
}
</script>
Step 4: Implementing Custom JavaScript Callbacks

Finally, let's create a custom JavaScript callback function that updates the Bokeh plot based on user interaction.

python 复制代码
def resize_plot():
    # Get the current plot dimensions
    plot_width = p.width
    plot_height = p.height

    # Resize the plot based on the new dimensions
    new_plot = bp.figure(width=plot_width * 1.5, height=plot_height)
    new_plot.line(df['x'], df['y'], line_width=2)
    plot_container.innerHTML = ''  # Clear the existing plot
    plot_container.appendChild(new_plot.html())
Step 5: Running the Application

To run the application, open the HTML file in a browser. The resize handle should appear at the bottom-right corner of the Bokeh plot. Clicking the handle will dynamically resize the plot.

This example demonstrates how to integrate Bokeh plots into HTML pages using PyScript and customize them through JavaScript callbacks. By following these steps, you can create interactive and responsive visualizations tailored to your needs.

相关推荐
互联网-小阿宇37 分钟前
【HTML+CSS+JS+VUE】web前端教程-31-css3新特性
前端·javascript·css
NoneCoder1 小时前
JavaScript系列(24)--内存管理机制详解
开发语言·javascript·ecmascript
han_1 小时前
为实现前端截图功能,我的dom-to-image踩坑之旅!
前端·javascript
不修×蝙蝠1 小时前
vue(七) vue进阶
前端·javascript·vue.js·前端框架·vue·ssm·进阶
甄同学1 小时前
【WPS】【WORD&WORD】【JavaScript】实现微软WORD自动更正的效果
开发语言·前端·javascript
ASER_19894 小时前
再谈Redux
javascript·typescript·react·redux·redux-toolkit·hooks·toolkit·html5移动前端·redux-hooks
一小只因程序猿4 小时前
《异步编程之美》— 全栈修仙《Java 8 CompletableFuture 对比 ES6 Promise 以及Spring @Async》
前端·javascript·jvm·spring·es6
ZTStory4 小时前
Webpack打包十六进制转十进制异常引发的白屏惨案
前端·javascript·webpack
桃园码工6 小时前
2_CSS3 背景 --[CSS3 进阶之路]
javascript·css3·css3 背景
marshalVS7 小时前
前端学习-事件对象与典型案例(二十六)
前端·javascript·学习