如何将Bokeh gridplot中的多个图表保存为独立PNG文件?
实现Bokeh多图表的独立查看与批量保存PNG
一、实现逐个目视检查与独立缩放
将原有的gridplot布局替换为Tabs组件,每个标签页对应一个图表,可切换查看单个图表,且每个图表的缩放、平移操作完全独立(若不需要轴联动,可移除共享轴的代码)。
二、添加批量保存PNG按钮
通过Bokeh的Button组件绑定自定义JavaScript逻辑,遍历所有图表并将每个图表导出为独立PNG文件下载。
完整实现代码
import numpy as np from bokeh.io import save from bokeh.layouts import column from bokeh.models import Button, CustomJS, TabPanel, Tabs from bokeh.plotting import figure x = np.linspace(0, 4 * np.pi, 100) y = np.sin(x) TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select" # 创建第一个图表 p1 = figure(title="Legend Example", tools=TOOLS, width=400, height=400) p1.circle(x, y, legend_label="sin(x)") p1.circle(x, 2 * y, legend_label="2*sin(x)", color="orange") p1.circle(x, 3 * y, legend_label="3*sin(x)", color="green") p1.legend.title = "Markers" # 创建第二个图表(移除轴共享,确保缩放独立) p2 = figure(title="Another Legend Example", tools=TOOLS, width=400, height=400) p2.circle(x, y, legend_label="sin(x)") p2.line(x, y, legend_label="sin(x)") p2.line( x, 2 * y, legend_label="2*sin(x)", line_dash=(4, 4), line_color="orange", line_width=2, ) p2.square(x, 3 * y, legend_label="3*sin(x)", fill_color=None, line_color="green") p2.line(x, 3 * y, legend_label="3*sin(x)", line_color="green") p2.legend.title = "Lines" # 用Tabs布局替代gridplot,实现逐个查看 tab1 = TabPanel(child=p1, title="图表1") tab2 = TabPanel(child=p2, title="图表2") tabs = Tabs(tabs=[tab1, tab2]) # 创建批量保存按钮 save_btn = Button(label="批量保存所有图表为PNG", button_type="success") # 绑定自定义JS逻辑,实现批量导出 save_btn.js_on_click(CustomJS(code=""" // 获取所有图表对象和对应标题 const plots = [p1, p2]; const plotTitles = ["Legend Example", "Another Legend Example"]; plots.forEach((plot, index) => { // 使用Bokeh内置的export_png方法导出图表 Bokeh.export_png(plot).then(png => { // 创建下载链接并触发下载 const a = document.createElement('a'); a.href = png; a.download = `${plotTitles[index]}.png`; a.click(); }); }); """, args={"p1": p1, "p2": p2})) # 组合布局:按钮 + 标签页图表 layout = column(save_btn, tabs) # 保存为HTML文件 save(layout)
关键说明
- 独立查看与缩放:
Tabs组件让你可以切换聚焦单个图表,每个图表的缩放、平移等操作仅作用于当前标签页内容,互不干扰;若需要保留轴联动需求,可重新添加p2.x_range = p1.x_range这类代码。 - 批量保存PNG:按钮点击后通过
Bokeh.export_png导出每个图表,自动生成对应标题命名的PNG文件并触发浏览器下载,无需后端额外依赖,静态HTML即可运行。 - 兼容性:该功能依赖浏览器Canvas API,主流浏览器均可正常支持。
内容的提问来源于stack exchange,提问作者aura
相关产品推荐
相关产品推荐

