Bokeh JS download plot image

55 views Asked by At

I want to download the plot image after manipulating it similar to what was discussed here. I can't get this code running without context so I created this minimal working example to try this out. Could someone help me get this workaround running?

A server application is not an option for my application. So I try this to get the download triggered on the client side:

import pandas as pd
from bokeh.models import Dropdown, Button, ColumnDataSource, CustomJS 
from bokeh.transform import factor_cmap
from bokeh.layouts import column 
from bokeh.plotting import show,figure


plot = figure(tools='tap, pan, wheel_zoom', width=1500, height=700 )
node_df = pd.DataFrame(data=dict(x=[1, 2, 3], y=[4, 5, 6], Option_A=['red', 'green', 'blue'], Option_B=['green', 'blue','red']))

node_source = ColumnDataSource(node_df)
mapper = factor_cmap(field_name='Fillcolor', palette=['red', 'green', 'blue'], factors = ['red','green','blue'])
node_renderer = plot.circle('x', 'y', source=node_source, size=10, color=mapper, selection_color=mapper, 
                              nonselection_color=mapper, selection_alpha=1, nonselection_alpha=0.2, line_color="black", 
                              selection_line_color="black", nonselection_line_color="black")
Dropdown_node_color = Dropdown(button_type="warning", menu = ['Option_A','Option_B'])

plot_export_button          = Button(label="Exportiere Plot", button_type="success")

callback_node_color = CustomJS(args=dict(renderer=node_renderer, source=node_source),code="""
    //renderer.glyph.field = this.item;
    //renderer.change.emit();
    var selected_column_data = source.data[this.item];
    source.data['Fillcolor'] = selected_column_data;
    source.change.emit();
""")
Dropdown_node_color.js_on_event("menu_item_click", callback_node_color)

plot_export_button_callback = CustomJS(args=dict(plot=plot), code="""
    
                                       
    // Get the plot view's SVG content
    //var svgData = plot.model.plot_view.get_svg();

    const blob = this.parent.export().to_blob();
    // Create a hidden link element to download the SVG
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'plot.png';
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
""")

plot_export_button.js_on_click(plot_export_button_callback)

layout = column(
    Dropdown_node_color,
    plot,
    plot_export_button
    )
show(layout)
0

There are 0 answers