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.

相关推荐
quitv13 分钟前
react脚手架配置别名
前端·javascript·react.js
Gazer_S2 小时前
【现代前端框架中本地图片资源的处理方案】
前端·javascript·chrome·缓存·前端框架
贺今宵4 小时前
通过$attrs传递的未指定名称的modelValue值在子组件中修改
前端·javascript
lifire_H8 小时前
Canvas在视频应用中的技术解析
前端·javascript·音视频
十八朵郁金香10 小时前
深入理解 JavaScript 中的 this 指向
开发语言·前端·javascript
贵州晓智信息科技10 小时前
使用 Three.js 转换 GLSL 粒子效果着色器
开发语言·javascript·着色器
linkcoco11 小时前
记录h5使用navigator.mediaDevices.getUserMedia录制音视频
前端·javascript·vue·音视频·js
Mh11 小时前
代码提交校验及提交规范的实践方案
前端·javascript·架构
昨日余光11 小时前
仅需三分钟,使用Vue3.x版本组件式风格实现一个消息提示组件!
前端·javascript·css·vue.js·typescript·html
软件开发技术深度爱好者11 小时前
验证码介绍及生成与验证(HTML + JavaScript实现)
javascript