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 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
Rowrey2 小时前
react+typescript,初始化与项目配置
javascript·react.js·typescript
祈澈菇凉6 小时前
Webpack的基本功能有哪些
前端·javascript·vue.js
记得早睡~7 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
庸俗今天不摸鱼7 小时前
Canvas进阶-4、边界检测(流光,鼠标拖尾)
开发语言·前端·javascript·计算机外设
[廾匸]8 小时前
cesium视频投影
javascript·无人机·cesium·cesium.js·视频投影
菲力蒲LY9 小时前
vue 手写分页
前端·javascript·vue.js
一丢丢@zml9 小时前
new 一个构造函数的过程以及手写 new
javascript·手写new
化作繁星10 小时前
React 高阶组件的优缺点
前端·javascript·react.js
zpjing~.~10 小时前
vue 父组件和子组件中v-model和props的使用和区别
前端·javascript·vue.js