Python 使用自定义函数在Bokeh中绘图?

Python 使用自定义函数在Bokeh中绘图?,python,bokeh,Python,Bokeh,有人知道是否/如何使用“自定义”功能使用Bokeh服务器在Bokeh中绘图吗?例如,我知道你可以使用 plot = figure(toolbar_location=None) plot.vbar(x='x', width=0.5, bottom=0, top='y', source=source) def mplot(source): p = pd.DataFrame() p['aspects'] = source.data['x'] p['importance'] =

有人知道是否/如何使用“自定义”功能使用Bokeh服务器在Bokeh中绘图吗?例如,我知道你可以使用

plot = figure(toolbar_location=None)
plot.vbar(x='x', width=0.5, bottom=0, top='y', source=source)
def mplot(source):
    p = pd.DataFrame()
    p['aspects'] = source.data['x']
    p['importance'] = source.data['y']
    plot = Bar(p, values='importance', label='aspects', legend=False)
    return plot
但是你怎么能用这样的东西来绘图呢

plot = figure(toolbar_location=None)
plot.vbar(x='x', width=0.5, bottom=0, top='y', source=source)
def mplot(source):
    p = pd.DataFrame()
    p['aspects'] = source.data['x']
    p['importance'] = source.data['y']
    plot = Bar(p, values='importance', label='aspects', legend=False)
    return plot
我目前的尝试是:


但它没有运行。我并不担心函数“update_samples_或_dataset”是否能正常工作,只需要显示初始绘图即可。任何帮助都将不胜感激。谢谢

我认为您仍然需要将
实例附加到
实例;一个
是一组图,本质上是一组细节,比如工具栏。

这就是你想要的吗?请注意,我没有使用从bokeh.charts导入的Bar函数,因为它不会在更新数据源时更新。 如果要继续使用bokeh.charts中的条形图,每次都需要重新创建绘图

注意:要运行此程序并进行更新工作,您需要从命令行执行
bokeh-serve--show plotfilename.py

from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models.widgets import Button
from bokeh.plotting import ColumnDataSource, figure
import random

def bar_plot(fig, source):
    fig.vbar(x='x', width=0.5, bottom=0,top='y',source=source, color="firebrick")
    return fig

def update_data():
    data = source.data
    data['y'] = random.sample(range(0,10),len(data['y']))
    source.data =data

button = Button(label="Press here to update data", button_type="success")
button.on_click(update_data)
data = {'x':[0,1,2,3],'y':[10,20,30,40]}
source = ColumnDataSource(data)
fig = figure(plot_width=650,
             plot_height=500,
             x_axis_label='x',
             y_axis_label='y')
fig = bar_plot(fig, source)
layout = layout([[button,fig]])
curdoc().add_root(layout)
编辑:请参见下面的一个方法,该方法绘制bokeh图,但根据需要使用数据帧中的数据。它还将在每次按下按钮时更新绘图。仍然需要使用命令
bokeh serve--show plotfilename.py

from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models.widgets import Button
from bokeh.plotting import ColumnDataSource
from bokeh.charts import Bar
import random
import pandas as pd

def bar_plot(source):
    df = pd.DataFrame(source.data)
    fig = Bar(df, values='y', color="firebrick")
    return fig

def update_data():
    data = {'x':[0,1,2,3],'y':random.sample(range(0,10),4)}
    source2 = ColumnDataSource(data)
    newfig = bar_plot(source2)
    layout.children[0].children[1] = newfig

button = Button(label="Press here to update data", button_type="success")
button.on_click(update_data)
data = {'x':[0,1,2,3],'y':[10,20,30,40]}
source = ColumnDataSource(data)
fig = bar_plot(source)
layout = layout([[button,fig]])
curdoc().add_root(layout)