点击按钮使用Bokeh从文件加载图形数据

6
我正在尝试在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)
1个回答

2
您需要加载这两个文件并将数据保存到一个 DataSource 对象中,以下是一个示例:
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)

感谢您的回答HYRY。这真的很好,唯一的问题是我有数百个数据文件,导致大量的数据。我不想预先加载所有数据,因为这需要很长时间。您知道一种在单击按钮时加载数据的方法吗? - Jon
2
然后您需要创建一个JavaScript函数来解析CSV文件,这里是一个例子:https://dev59.com/5ms05IYBdhLWcg3wIObS - HYRY
非常感谢,这些答案的组合解决了我的问题。非常感激。 - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接