【问题标题】:Plot multiple lines with Python Bokeh fom the same dataset使用 Python Bokeh 从同一数据集中绘制多条线
【发布时间】:2021-02-03 09:03:42
【问题描述】:

是否有可能使用 Bokeh 实现像 sample1 这样的图? Sample1 是使用 Matplotlib 创建的。我的目标是在地图上绘制多条彼此分开的短线。但是这些行共享相同的源,只是与源内部的不同部分。

我已经写了一个小脚本,但结果不是很好……(参见示例 2)。我的脚本在地图上绘制了 3 条不同的线。不幸的是,这些线条是连在一起的。

在 Matplotlib 中,它与 for 循环一起使用。但在 Bokeh 中,我尝试使用滑块以交互方式选择我喜欢查看的数据。

样品1

样本2

这是我的代码:

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, GMapOptions, CustomJS
from bokeh.plotting import gmap, ColumnDataSource, figure
from bokeh.layouts import column, row
from bokeh.models.widgets import RangeSlider 
import numpy as np

# data set
lon = [[48.7886, 48.7887, 48.7888, 48.7889, 48.789], 
        [48.7876, 48.7877, 48.78878, 48.7879, 48.787], 
        [48.7866, 48.7867, 48.7868, 48.7869, 48.786]]
lat = [[8.92, 8.921, 8.922, 8.923, 8.924],
        [8.91, 8.911, 8.912, 8.913, 8.914],
        [8.90, 8.901, 8.902, 8.903, 8.904]]

# convert data set in 1D for callback function (JS slice)
lat1D = []
lon1D = []
for k in range(len(lon)):
    lat1D += lat[k]
    lon1D += lon[k]

# define source and map
source = ColumnDataSource(data = {'x': lon1D, 'y': lat1D})

map_options = GMapOptions(lat=48.7886, lng=8.92, map_type="satellite", zoom=13)

p = gmap("MY_API_KEY", map_options, title="Trajectory Map")

# plot lines on map
# for loops do not work like in matplotlib...
for j in range(0, len(lon1D), len(lon)):
    for i in range(j, j + len(lon)):
        p.line('y', 'x', source=source, line_width=0.4)

# slider to limit plotted data
range_slider = RangeSlider(title="Data Range Slider: ", start=0, end=len(lon1D), value=(0, len(lon1D)), step=1) 

callback = CustomJS(args=dict(source=source, slider=range_slider, long=lon1D, lati=lat1D, lenght=len(lon)), code="""
    var data = source.data;
    const start = slider.value[0];
    const end = slider.value[1];
    
    data['x'] = long.slice(start, end)
    data['y'] = lati.slice(start, end)

    source.change.emit();
    """)

range_slider.js_on_change('value', callback)

# Layout to plot and output
layout = row(
    p, range_slider)

output_file("diag_plot_bike_data.html")

show(layout)

【问题讨论】:

    标签: python matplotlib bokeh bokehjs pandas-bokeh


    【解决方案1】:

    任何可以用 Matplotlib 绘制的东西,都可以用 Bokeh 绘制。有时代码多一点,有时代码少一点。

    你的代码中发生的事情太多了,所以我会用纯文本来回答:

    【讨论】:

    • 感谢您的回答。战争真的很有帮助!我决定为 range_slider 使用 on_change 而不是 js_on_change。现在我的回调函数遇到了一些问题......我想用 range_slider 更改我的地块的 IndexFilter。当我直接在回调中访问我的 plot.view 时,我该如何完成这项任务,它不起作用...:/
    • 这似乎是一个完全独立的问题。请问可以用完整的代码问一个新问题吗?只要确保把bokeh标签放在那里,我会检查出来的。
    猜你喜欢
    • 2015-10-09
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多