Search code examples
pythonpython-3.xpandasbokeh

Bokeh Server: Tap on Scatter to Show additional Data in Bar Plot


I have a DataFrame which holds the data I want to plot in a scatter plot. The DataFrame has far more information than only the columns needed for the scatter x and y data.

I want to show the additional data as hover (which is not the problem) but also if I Tap-select one data point in the scatter the additional data in the other columns of the ColumnDataSource shall be plottet in a Bar Plot.

My main Problem is to get the bar plot to accept the data stored in the one selected row of the ColumnDataSource. Everything I have seen uses column based data to feed it to the bar plot.

I was half-way through a workaround where I use the selected row of the ColumnDatasource transform it back to a DataFrame then transpose it (so it is column based) and then back to a ColumnDataSource but this can not be the intention of the creators of bokeh, right?

I stripped my Problem down to a minimalistic code snippet:

df = pd.DataFrame({"x": [1,2,3,4,5,6],
                   "y": [6,5,4,3,2,1],
                   "cat1": [11,12,13,14,15,16],
                   "cat2": [100,99,98,97,96,95]})

SRC = ColumnDataSource(df)

def Plot(doc):
    
    def callback(event):
        SELECTED = SRC.selected.indices
        bplot = make_bPlot(SELECTED)
        
    def make_bPlot(selected):
        #Here is my question:
        #How to feed the row-wise data of the SRC to the barplot?
        b = figure(x_range=["cat1", "cat2"])
        b.vbar(x=["cat1", "cat2"], top=["cat1", "cat2"], source=SRC)
        
        return b
        
    TOOLTIPS = [
        ("x", "@x"),
        ("y", "@y"),
        ("Category 1", "@cat1"),
        ("Category 2", "@cat2")]

    TOOLS="pan,wheel_zoom,zoom_in,zoom_out,box_zoom,reset,tap"
    cplot = figure(tools = TOOLS, tooltips=TOOLTIPS)
    cplot.circle("x", "y", source=SRC)
    
    bplot = make_bPlot(None) # init
       
    
    taptool = plot.select(type=TapTool)
    cplot.on_event(Tap, callback)
    
    
    layout = column(cplot, bplot)
    doc.add_root(layout)

Thanks in advance.


Solution

  • I got my answer from the Bokeh Discourse Forum: https://discourse.bokeh.org/t/tap-on-scatter-to-show-additional-data-in-bar-plot/6939