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.

相关推荐
一夜枫林1 小时前
uniapp自定义拖拽排列
前端·javascript·uni-app
良艺呐^O^1 小时前
uniapp实现app自动更新
开发语言·javascript·uni-app
拉不动的猪4 小时前
前端自做埋点,我们应该要注意的几个问题
前端·javascript·面试
烛阴5 小时前
Node.js中必备的中间件大全:提升性能、安全与开发效率的秘密武器
javascript·后端·express
小杨升级打怪中5 小时前
前端面经-JS篇(三)--事件、性能优化、防抖与节流
前端·javascript·xss
鱼樱前端6 小时前
前端必知必会:JavaScript 对象与数组克隆的 7 种姿势,从浅入深一网打尽!
前端·javascript
yzhSWJ6 小时前
Spring Boot中自定义404异常处理问题学习笔记
java·javascript
zyk_5208 小时前
前端渲染pdf文件解决方案-pdf.js
前端·javascript·pdf
沉迷...8 小时前
手动实现legend 与 echarts图交互 通过js事件实现图标某项的高亮 显示与隐藏
前端·javascript·echarts
皮实的芒果9 小时前
前端实时通信方案对比:WebSocket vs SSE vs setInterval 轮询
前端·javascript·性能优化