bokeh - plot a different column using customJS

前端 未结 1 1294
旧时难觅i
旧时难觅i 2020-12-17 06:11

I have a dataframe of multiple columns. First two columns are x and y coordinates and the rest columns are different property values for (x,y) pairs.

import         


        
相关标签:
1条回答
  • 2020-12-17 06:45

    I have included an example with comments inline with the code. The main important steps are to write the javascript code that is executed each time the selected option on the widget changes. The code simply needs to just re-assign which of the columns is set to the values for the 'y' column of the datasource.

    The other issue is that your data is just x and y points. The patches glyph will require a different data structure which defines the boundaries of the patches. I believe there are better ways to make a heatmap in bokeh, there should be numerous examples on stack overflow and the bokeh docs.

    import pandas as pd
    import numpy as np
    
    from bokeh.io import show
    from bokeh.layouts import widgetbox,row
    from bokeh.models import ColumnDataSource, CustomJS
    
    df = pd.DataFrame()
    df['x'] = np.random.randint(1,1000,1000)
    df['y'] = np.random.randint(1,1000,1000)
    df['val1'] = np.random.randint(1,1000,1000)
    df['val2'] = np.random.randint(1,1000,1000)
    df['val3'] = np.random.randint(1,1000,1000)
    
    from bokeh.plotting import figure
    from bokeh.models import LinearColorMapper
    from bokeh.palettes import RdYlBu11 as palette
    
    p = figure(x_range=(0,1000),y_range=(0,1000))
    source = ColumnDataSource(df)
    source_orig = ColumnDataSource(df)
    color_mapper = LinearColorMapper(palette=palette)
    p.rect('x', 'y', source=source,width=4,height=4,
              color={'field': 'val1', 'transform':color_mapper})
    
    from bokeh.models.widgets import Select
    select = Select(title="Option:", value="val1", options=["val1","val2","val3"])
    
    callback = CustomJS(args={'source':source},code="""
            // print the selectd value of the select widget - 
            // this is printed in the browser console.
            // cb_obj is the callback object, in this case the select 
            // widget. cb_obj.value is the selected value.
            console.log(' changed selected option', cb_obj.value);
    
            // create a new variable for the data of the column data source
            // this is linked to the plot
            var data = source.data;
    
            // allocate the selected column to the field for the y values
            data['y'] = data[cb_obj.value];
    
            // register the change - this is required to process the change in 
            // the y values
            source.change.emit();
    """)
    
    # Add the callback to the select widget. 
    # This executes each time the selected option changes
    select.callback = callback
    show(row(p,select))
    
    0 讨论(0)
提交回复
热议问题