散景回调以更改源数据和悬停工具提示

时间:2019-05-24 22:53:29

标签: bokeh

我正在使用Bokeh绘制X / Y数据。

分别创建X和Y值,并将其合并到一个数据表中以供图表使用。

有人可以解释一下完成以下任务的最佳方法吗?

  • 运行更新源回调时,创建的全局new_df未被用作源。这是因为新的数据源具有新的列名/形状吗?

  • 仅针对原始X / Y数据初始化悬浮工具设置。因此,它不会拉入第二个new_df示例中的“ Extra_Info”列。  使悬停工具接受多余的列的最佳方法是什么?  重新设置回调函数中的悬停工具是这样做的方法吗?

这是我的半职业例子。 感谢任何帮助。

#Imports
import bokeh
import numpy as np
import pandas as pd
from random import randint
from bokeh.layouts import column, row
from bokeh.models.widgets import Button
from bokeh.plotting import figure, curdoc, show
from bokeh.models import ColumnDataSource, HoverTool


#Creating first data source
df1 = pd.DataFrame(np.random.randint(0, 100, size = (3000, 2)), 
                   columns = ["X", "Y"], 
                   index = [str(i) for i in range(1, 3000 + 1)])

pointchart_source = ColumnDataSource(df1)
pointchart = figure(plot_width = 800, plot_height = 700)
pointchart_glyph = pointchart.circle("X", "Y", source = pointchart_source, size = 3.5)

hover=HoverTool(tooltips = [("(X,Y)", "($x{1,111},$y{1,111})")])
pointchart.add_tools(hover)



#Button and calback to switch source data
def on_switch_button_click():
    global new_df
    pointchart_source.data = ColumnDataSource.from_df(new_df)

    #Should probably plugging in new data as a dictionary.
    #pointchart_source.data = {'X': newdataframe['X'].values, 'Y': newdataframe['Y'].values, 'index': newdataframe.index.values}

switch_button = Button(label = "Switch", button_type = "success")
switch_button.on_click(on_switch_button_click)


#Option I
#Making a changed data source. Combined two 1D into a DF.
x=pd.DataFrame({'X_Value_For_Plot':[randint(1, 100) for i in range(0,10)], 'Common_Column':['a','b','c','d','e','f','g','h','i','j']})
y=pd.DataFrame({'Y_Value_For_Plot':[randint(1, 100) for i in range(0,10)], 'Common_Column':['a','b','c','d','e','f','g','h','i','j']})

new_df = x.merge(y,on='Common_Column')



#Option II
#Making another data source with extra columns for the Hover Tool. 
x=pd.DataFrame({'X_Value_For_Plot':[randint(1, 100) for i in range(0,10)], 
                'X_Extra_Info':['abc','cba','sgc','ddh','eda','fdv','gdy','hsy','dsi','jdu'],
                'Common_Column':['a','b','c','d','e','f','g','h','i','j']})


y=pd.DataFrame({'Y_Value_For_Plot':[randint(1, 100) for i in range(0,10)], 
                'Y_Extra_Info':['hsa','bsv','dyc','sdd','eac','eyf','scg','dyh','isq','jst'],
                'Common_Column':['a','b','c','d','e','f','g','h','i','j']})

new_df = x.merge(y,on='Common_Column')

1 个答案:

答案 0 :(得分:1)

AFAICT您正在使事情变得不必要的复杂。如果可以分别为每个列生成列表,数组或序列,这似乎就是您所说的话,那么您可以自己构建字典:

source.data = {
    'X': the_x_data,
    'Y': the_y_data,
    'X_Extra_Info': the_extra_data,
}

只要所有dict值具有相同的长度(在任何情况下,它们都必须为 ),就无需先将它们放在Pandas中。