代码之家  ›  专栏  ›  技术社区  ›  Kexin Xu

如何使用bokeh将vbar与圆图链接?

  •  1
  • Kexin Xu  · 技术社区  · 7 年前

    我有三个基于同一数据集的图。如何链接所有三个图,以便在vbar图中选择某个物种时,两个散点图也会更改为仅绘制该物种中的点。

    感谢您的帮助~

    from bokeh.sampledata.iris import flowers
    from bokeh.plotting import figure, output_file, show
    from bokeh.models import ColumnDataSource, CategoricalColorMapper
    from bokeh.layouts import column, row
    
    #color mapper to color data by species
    mapper = CategoricalColorMapper(factors = ['setosa','versicolor', 'virginica'],\
                                     palette = ['green', 'blue', 'red'])
    
    
    output_file("plots.html")
    
    #group by species and plot barplot for count
    species = flowers.groupby('species')
    
    source = ColumnDataSource(species)
    
    p = figure(plot_width = 800, plot_height = 400, title = 'Count by Species', \
               x_range = source.data['species'], y_range = (0,60),tools = 'box_select')
    
    p.vbar(x = 'species', top = 'petal_length_count', width = 0.8, source = source,\
           nonselection_fill_color = 'gray', nonselection_fill_alpha = 0.2,\
           color = {'field': 'species', 'transform': mapper})
    
    labels = LabelSet(x='species', y='petal_length_count', text='petal_length_count', 
                  x_offset=5, y_offset=5, source=source)
    
    p.add_layout(labels)
    
    
    
    #scatter plot for sepal length and width
    source1 = ColumnDataSource(flowers)
    p1 = figure(plot_width = 800, plot_height = 400, tools = 'box_select', title = 'scatter plot for sepal')
    
    p1.circle(x = 'sepal_length', y ='sepal_width', source = source1, \
              nonselection_fill_color = 'gray', nonselection_fill_alpha = 0.2, \
              color = {'field': 'species', 'transform': mapper})
    
    
    #scatter plot for petal length and width
    p2 = figure(plot_width = 800, plot_height = 400, tools = 'box_select', title = 'scatter plot for petal')
    
    p2.circle(x = 'petal_length', y ='petal_width', source = source1, \
              nonselection_fill_color = 'gray', nonselection_fill_alpha = 0.2, \
              color = {'field': 'species', 'transform': mapper})
    
    
    #show all three plots
    show(column(p, row(p1, p2)))
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Eugene Pakhomov    7 年前

    我认为目前还没有这方面的功能。但是你可以明确地将两者联系起来 ColumnDataSource 带a的s CustomJS 回调:

    from bokeh.models import CusomJS
    
    source = ColumnDataSource(species)
    source1 = ColumnDataSource(flowers)
    source.js_on_change('selected', CustomJS(args=dict(s1=source1), code="""
        const indices = cb_obj.selected['1d'].indices;
        const species = new Set(indices.map(i => cb_obj.data.species[i]));
        s1.selected['1d'].indices = s1.data.species.reduce((acc, s, i) => {if (species.has(s)) acc.push(i); return acc}, []);
        s1.select.emit();
    """))
    

    请注意,此回调仅将条形图中的选择同步到散点图。要在散点图上做出影响条形图的选择,您必须编写一些额外的代码。