2022-08-20

Bokeh: How to display interactive written text dependent by dropdown menus selections

this is my first question on Stack Overflow, I hope I'm doing it right. I'm working on a Jupyter Notebook, Python 3.9, and Bokeh 2.4.3, and I know nothing of JavaScript. I already built some working code that plots data from a dataframe by selecting the columns I want to inspect as x and y through two dropdown menus:

from bokeh.io import show, output_notebook
from bokeh.models import ColumnDataSource, Select, Column, Row, CustomJS, PreText
from bokeh.plotting import figure
import pandas as pd
output_notebook()

data = {'moo': [1, 2, 3, 4],
        'woof': [20, 21, 19, 18],
        'purr': [33, 45, 12, 16]}
df = pd.DataFrame(data)
source = ColumnDataSource(df)

p = figure(plot_height=500, plot_width=500, x_axis_label="moo", y_axis_label="woof")
r = p.circle(x='moo', y='woof', source=source)
selecty = Select(value='woof', title='y-axis', options=list(df.columns))
selectx = Select(value='moo', title='x-axis', options=list(df.columns))
cby = CustomJS(args=dict(r=r, select=selecty, yaxis=p.yaxis), code="""
    // tell the glyph which field of the source y should refer to
    r.glyph.y.field = select.value;
    // change axis label accordingly
    yaxis[0].axis_label = select.value;
    // manually trigger change event to re-render
    r.glyph.change.emit()
""")
cbx = CustomJS(args=dict(r=r, select=selectx, xaxis=p.xaxis), code="""
    // tell the glyph which field of the source y should refer to
    r.glyph.x.field = select.value;
    // change axis label accordingly
    xaxis[0].axis_label = select.value;
    // manually trigger change event to re-render
    r.glyph.change.emit()
""")
selecty.js_on_change('value', cby)
selectx.js_on_change('value', cbx)
show(Row(Column(selecty, selectx), p))

So far, so good. Now I'd like to add interactive text taken from the correlation matrix obtained from the following code: corrMatrix = df.corr() so that, for example, when I select to plot moo as abscissa and woof as ordinate, the code will print -0.80 right below the menus (therefore, outside the plot). I suppose I should use PreText from bokeh.models, but I have no clue about the JS code I should use. Thanks in advance.



No comments:

Post a Comment