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:

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.

<!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

<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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值