Search code examples
javascriptpythonbokeh

How to use Javascript in Bokeh map?


I want to change the name of a variable as I will use it later to specify exactly what I need to plot. However, Javascript is giving me more trouble than I thought. I am using a dropdown menu and as I select a value , the variable should also change, but that is not happening. Any suggestions? I am still very new to Javascript, so any advice would be appreciated

column="justastring"


 selecthandler = CustomJS(args=dict(column=column), code="""
   var col=column.value;
   
  if (cb_obj.value=="Ozone"){
      col='OZONE';   
   }
   if (cb_obj.value=="O2"){
       col='O_2';
   }

   if(cb_obj.value=="DO2"){
        col='DO2'; 
   }
   
   


    column.change.emit();
    """)

  select.js_on_change('value',selecthandler)

Solution

  • You didn't provide a runnable code so I've created a minimal example from scratch:

    from bokeh.layouts import column
    from bokeh.models import ColumnDataSource, Select, CustomJS
    from bokeh.plotting import figure, show
    from bokeh.transform import linear_cmap
    from bokeh.palettes import Viridis3
    
    ds = ColumnDataSource(dict(x=[0, 1, 2],
                               a=[0, 0, 1],
                               b=[3, 2, 1]))
    p = figure()
    
    renderer = p.rect(x='x', y=0, width=1, height=1,
                      fill_color=linear_cmap('a', Viridis3, 0, 1), source=ds)
    
    s = Select(value='a', options=['a', 'b'])
    s.js_on_change('value',
                   CustomJS(args=dict(r=renderer, ds=ds),
                            code="""
                                const c = cb_obj.value;
                                const fc = r.glyph.fill_color;
                                fc.field = c;
                                fc.transform.low = Math.min(...ds.data[c]);
                                fc.transform.high = Math.max(...ds.data[c]);
                                // If you don't change `low` and `high` fields above, you will
                                // have to uncomment this line to trigger value change signals
                                // so that the glyphs are re-rendered.
                                //r.glyph.fill_color = fc;
                            """))
    
    show(column(s, p))