2016-01-08 44 views
5

我想使用Bokeh中的切換按鈕來創建一個交互式網站,用戶可以點擊切換按鈕來選擇繪製哪些圖。加載圖形數據從文件按鈕點擊與景

這些按鈕可以從文本文件(包含兩列x和y數據)加載數據。數據文件有兩列包含由空格分隔的x和y數據。

當選擇切換按鈕時,將繪製相應的數據,當取消切換按鈕時將刪除該圖。

我目前無法將參數傳遞給回調事件,有可能嗎?

from bokeh.io import vform 
from bokeh.models import CustomJS, ColumnDataSource 
from bokeh.models.widgets import Toggle 
from bokeh.plotting import figure, output_file, show 

output_file("load_data_buttons.html") 

x = [0] 
y = x 

source = ColumnDataSource(data=dict(x=x, y=y)) 

plot = figure(plot_width=400, plot_height=400) 
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) 

callback = CustomJS(args=filename,dict(source=source), code=""" 
     var data = source.get('data'); 
     console.log(filename) 
     x = data['x'] 
     y = data['y'] 
     #load data stored in the file name and assign to x and y 
     source.trigger('change'); 
    """) 

toggle1 = Toggle(label="Load data file 1", type="success",callback=callback("data_file_1.txt")) 
toggle2 = Toggle(label="Load data file 2", type="success",callback=callback("data_file_2.txt")) 

layout = vform(toggle1, toggle2, plot) 

show(layout) 

回答

2

您應加載這兩個文件和數據保存到數據源對象,這裏有一個例子:

from bokeh.io import vplot 
import pandas as pd 
from bokeh.models import CustomJS, ColumnDataSource 
from bokeh.models.widgets import Button 
from bokeh.plotting import figure, output_file, show 

output_file("load_data_buttons.html") 

df1 = pd.read_csv("data_file_1.txt") 
df2 = pd.read_csv("data_file_2.txt") 

plot = figure(plot_width=400, plot_height=400) 

source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1])) 
source2 = ColumnDataSource(data=dict(x1=df1.x.values, y1=df1.y.values, 
            x2=df2.x.values, y2=df2.y.values)) 

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) 

callback = CustomJS(args=dict(source=source, source2=source2), code=""" 
     var data = source.get('data'); 
     var data2 = source2.get('data'); 
     data['x'] = data2['x' + cb_obj.get("name")]; 
     data['y'] = data2['y' + cb_obj.get("name")]; 
     source.trigger('change'); 
    """) 

toggle1 = Button(label="Load data file 1", callback=callback, name="1") 
toggle2 = Button(label="Load data file 2", callback=callback, name="2") 

layout = vplot(toggle1, toggle2, plot) 

show(layout) 
+0

感謝您的回答HYRY。這真的很不錯,唯一的麻煩是我有數百個數據文件導致了很多數據。我不想事先將它預先加載,因爲這需要很長時間。你知道點擊按鈕時加載數據的方法嗎? – Jon

+1

然後你需要創建一個javascript函數來解析csv文件,這裏是一個例子:http://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript – HYRY

+0

非常感謝,這個答案的組合解決了我的問題。非常感激。 – Jon

相關問題