You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Bokeh交互式图表导出至其他文件用于Panel可视化仪表盘?

实现Bokeh图表复用至Panel仪表盘(保留交互性)

完全可以实现将单个文件中的Bokeh图表集成到Panel仪表盘中,且能完整保留图表的交互功能。以下是两种最实用的方案:


方案1:直接复用Bokeh对象(推荐)

将Bokeh图表的创建逻辑封装为函数,在Panel文件中导入并调用,直接生成可交互的Bokeh组件。这种方式既能保留所有原生交互,还能通过Python代码灵活控制图表参数,是集成到Panel的最优解。

步骤示例:

  1. 封装Bokeh图表函数(比如保存为bokeh_pie.py):
import pandas as pd
from math import pi
from bokeh.plotting import figure
from bokeh.models import CustomJS, Slider, HoverTool, ColumnDataSource
from bokeh.layouts import column
from bokeh.transform import cumsum
import colorcet

def create_disease_pie_chart():
    # 数据准备
    data = {"Year": [1990, 1991, 1992],
            "Meningitis": [2159, 1592, 3914],
            "Alzheimer": [1116, 842, 534],
            "Parkinson": [371, 2376, 1675],
            "Malaria": [93, 189, 231]    
    }
    df = pd.DataFrame(data).set_index("Year")
    df_transposed = df.transpose()

    year_dfs = []
    for year in df_transposed.columns:
        year_df = df_transposed[year].to_frame(name="Deaths")
        year_df.index.name = "Disease"
        year_df["Percent"] = 100 * year_df["Deaths"]/year_df["Deaths"].sum()
        year_df["angle"] = year_df["Deaths"]/year_df["Deaths"].sum() * 2 * pi
        year_df["start_angle"] = pi/2 - (year_df["angle"].cumsum() - year_df["angle"])
        year_df["end_angle"] = pi/2 - year_df["angle"].cumsum()
        year_df['color'] = list(map(lambda x: colorcet.b_glasbey_category10[x], range(len(year_df))))
        year_dfs.append(year_df)

    year_dicts = [dict(ColumnDataSource(df).data) for df in year_dfs]

    # 图表创建
    plot = figure(height=550, width=650, title="Diseases", x_range=(-0.6, 1.0))
    plot_source = ColumnDataSource(year_dicts[0])
    plot.wedge(x=0, y=1, radius=0.6, source=plot_source,
             start_angle="start_angle", end_angle="end_angle", direction="clock",
            line_color="white", legend_field='Disease', fill_color='color')

    # 交互配置
    hover = HoverTool(tooltips=[("Disease", "@{Disease}"),
                                ("Deaths", "@Deaths"),
                                ("Percent", "@Percent{f0.0} %")])
    plot.add_tools(hover)
    plot.axis.visible = False
    plot.grid.grid_line_color = None
    plot.title.text_font_size = '16pt'
    plot.toolbar.active_drag = None
    plot.toolbar_location = None

    # 滑块与JS回调
    slider = Slider(start=1990, end=1992, value=1990, step=1, title="Select year")
    callback = CustomJS(args=dict(plot_source=plot_source, sources=year_dicts), code="""
        const year_select = cb_obj.value
        plot_source.data = sources[year_select - 1990]
    """)
    slider.js_on_change('value', callback)

    return column(slider, plot)
  1. 在Panel仪表盘中调用(比如保存为dashboard.py):
import panel as pn
from bokeh_pie import create_disease_pie_chart

# 初始化Panel的Bokeh支持
pn.extension('bokeh')

# 创建图表组件
pie_chart = create_disease_pie_chart()

# 构建仪表盘布局
dashboard = pn.Column(
    "# 疾病死亡数据仪表盘",
    pie_chart,
    # 可添加其他Panel组件(如文本、其他图表、交互控件)
    width=900
)

# 启动仪表盘
dashboard.show()

这种方式下,Bokeh的滑块切换、hover提示等交互功能完全保留,还能和Panel的其他组件无缝整合。


方案2:加载已导出的Bokeh HTML

如果已经将Bokeh图表导出为HTML文件,也可以直接用Panel加载,前端交互功能依然有效(因为Bokeh导出的HTML包含了所有所需的JS和数据,无需后端Python运行)。

步骤示例:

  1. 先导出Bokeh HTML:
    在你的Bokeh代码末尾添加保存逻辑:
from bokeh.io import save
save(layout, filename="pie_chart.html")
  1. 在Panel中加载HTML:
import panel as pn

pn.extension()

# 加载HTML文件
pie_chart_html = pn.pane.HTML("pie_chart.html", width=700, height=600)

# 构建仪表盘
dashboard = pn.Column(
    "# 疾病死亡数据仪表盘",
    pie_chart_html
)

dashboard.show()

这种方式适合已有现成HTML文件的场景,但缺点是无法通过Python代码动态修改图表参数(比如调整年份范围),仅能保留前端原生交互。

内容的提问来源于stack exchange,提问作者AlZ11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:27:55