Pandas 为bokeh散点图选择数据帧行

Pandas 为bokeh散点图选择数据帧行,pandas,bokeh,Pandas,Bokeh,使用Bokeh中的下拉菜单从数据帧中选择特定行的最佳方法是什么?我尝试使用下面的修改脚本绘制iris,但服务器上只有一个空白屏幕: import pandas as pd from bokeh.models import ColumnDataSource, ColorBar, CategoricalColorMapper from bokeh.plotting import figure, show from bokeh.palettes import Spectral6 from bokeh

使用Bokeh中的下拉菜单从数据帧中选择特定行的最佳方法是什么?我尝试使用下面的修改脚本绘制iris,但服务器上只有一个空白屏幕:

import pandas as pd

from bokeh.models import ColumnDataSource, ColorBar, CategoricalColorMapper
from bokeh.plotting import figure, show
from bokeh.palettes import Spectral6
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.layouts import widgetbox

from bokeh.sampledata.iris import flowers as df
source = ColumnDataSource(df)

mapper = CategoricalColorMapper(
    factors=['setosa', 'virginica', 'versicolor'], 
    palette=['red', 'green', 'blue']) 

plot = figure(x_axis_label='petal_length', y_axis_label='sepal_length',plot_width=400,plot_height=400)
plot.circle('petal_length', 'sepal_length',size=4, source=source, 
            color={'field': 'species', 
                   'transform': mapper}) 

species=list (df['species'].unique())

menu = Select(options=species,value='setosa', title='Species')

# Add callback to widgets
def callback(attr, old,new):
    source_data=pd.DataFrame(source.data)
    new_data= source_data.loc[source_data['species']==menu.value]
    new_data_dict=dict (new_data)
    source.data=new_data_dict

menu.on_change('value', callback)

layout = column(menu, plot)
curdoc().add_root(layout)

第一部分是一个给定的示例,因此没有菜单的图表工作正常。我的问题是回调函数的设计,用于从数据帧中选择特定的行

您似乎忘记了为.loc指定行输入,我假设您希望所有行的物种列都等于menu.value。尝试使用此选项代替新的_数据分配

new_data = source_data.loc[:,source_data['species']==menu.value]
或者,如果没有.loc,则可以使用布尔掩蔽

new_data = source_data[source_data['species'] == menu.value]
  • 您忘记导入
    选择
    。从bokeh.models.widgets导入选择添加
    
    
  • 请注意您是如何在回调中覆盖数据源的,因此在一次选择之后,除了一个之外,所有物种数据都将消失。因此,您需要更改切换数据的逻辑

  • 谢谢我尝试了两种建议,但结果是一样的!我将列数据源的准备放在一个函数中,从回调调用这个函数。问题解决了,谢谢。