Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Bokeh滑块自定义JS回调_Python_Pandas_Callback_Slider_Bokeh - Fatal编程技术网

Python Bokeh滑块自定义JS回调

Python Bokeh滑块自定义JS回调,python,pandas,callback,slider,bokeh,Python,Pandas,Callback,Slider,Bokeh,我是Bokeh的新手,尝试使用CustomJS实现滑块回调。我将销售数据按年、月、日分组。根据滑块值(1-12),必须在绘图上更改我的月度数据。下面是我的代码: 滑块值(0-12)-月份数 X轴:天(1-30) y轴:销售 df3=df df3['Date2'] = pd.to_datetime(df['Inv Date']) df3.set_index('Date2', inplace=True) df3['month'] = df3.index.month df3['year'] =

我是Bokeh的新手,尝试使用CustomJS实现滑块回调。我将销售数据按年、月、日分组。根据滑块值(1-12),必须在绘图上更改我的月度数据。下面是我的代码: 滑块值(0-12)-月份数 X轴:天(1-30) y轴:销售

df3=df


df3['Date2'] = pd.to_datetime(df['Inv Date'])
df3.set_index('Date2', inplace=True)


df3['month'] = df3.index.month
df3['year'] = df3.index.year
df3['day'] = df3.index.day

df3['Dateday'] = pd.to_datetime(df3[['year','month', 'day']])

source1=df3.groupby(['year','month','day'], as_index = False).sum()

current_month=ColumnDataSource(source1[source1['year']== dt.now().year])


hover3 = HoverTool(
        tooltips = [
            ('day', '@day'),
            ('Sales','@{Sales}{0,0}'),
            ],
        formatters = {
            'day': 'datetime',
            'Sales': 'numeral'}
       )

 p =  figure(
 title='YEARLY SALES',  
 plot_width=600, 
 plot_height=400, 
 min_border=3,

tools = [hover3,'box_zoom','wheel_zoom', 'pan','reset'],  
toolbar_location="above")
p.vbar(x='day', top='Sales', width=0.2, color='#e8bc76', 
source=current_month)
p.xaxis.axis_label = 'Day'
p.xaxis.axis_label_text_font_style = 'normal'
p.xaxis.axis_label_text_font_size = '12pt'
p.yaxis[0].formatter = NumeralTickFormatter(format="0,0")




callback = CustomJS(args=dict(source=current_month), code="""       
        var f = slider.get('value');
        var data = source.data; 

        data1=current_month[current_month['month']== f]
        day=data1[data1['day']]
        Sales=data1[data1['Sales']]
source.trigger('change');
    """)
slider = Slider(start=1, end=12, value=1, step=1, title="power",             
callback=callback)

layout = column(slider, p)

show(layout)

谁能帮帮我吗。我被困在这里,无法根据自定义回调筛选数据帧

如果您想使用可以调用本机python回调函数的
bokeh-serve
,这将相当快。这也可以使用javascript回调
CustomJS
实现

由于我没有您的数据,我使用以下代码生成了一个虚拟数据-

import pandas as pd
import random
from datetime import timedelta

df = pd.DataFrame({'base' : ["2017-01-01" for t in range(10000)],
    'Date' : [random.randint(0, 1035) for t in range(10000)], 
                   'Sales' : [random.random() for t in range(10000)]})
df['base'] = pd.to_datetime(df['base'])
df["Date2"] = df.apply(lambda x: x["base"] + timedelta(days=x['Date']), axis=1)
df.drop(['base', 'Date'], axis=1, inplace=True)
这将在2017年至2019年间产生10000行随机销售。在下面的例子中,我只对2017年进行了筛选

在下一步中,我将生成两个
ColumnDataSource
——一个用于所有2017年数据,另一个仅用于2017年第1个月的数据——以创建初始图形。第二个将用于生成
vbar

from bokeh.models.widgets import Slider
from bokeh.layouts import widgetbox, column
from bokeh.models import Slider, ColumnDataSource, CustomJS
from bokeh.plotting import figure, curdoc
from bokeh.core.properties import value
from bokeh.models.ranges import FactorRange
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.models import ColumnDataSource, CDSView, IndexFilter, BooleanFilter, HoverTool

df.set_index('Date2', inplace=True)
df['month'] = df.index.month
df['year'] = df.index.year
df['day'] = df.index.day
source1=df.groupby(['year','month','day'], as_index = False).sum()
source = source1[source1['year']== 2017]
sourcex = source[source['month'] ==1]
Overall=ColumnDataSource(source)
Curr=ColumnDataSource(sourcex)
boolinit = source['month']==1
view = CDSView(source=Overall, filters=[BooleanFilter(boolinit)])
hover3 = HoverTool(tooltips = [('day', '@day'),('Sales','@{Sales}{0,0}')],
                   formatters = {'day': 'datetime','Sales': 'numeral'})

p =  figure(title='YEARLY SALES',  plot_width=600, plot_height=400, min_border=3,
tools = [hover3,'box_zoom','wheel_zoom', 'pan','reset'],  
toolbar_location="above")

r = p.vbar(x='day', top='Sales', width=0.2, color='#e8bc76', source=Curr)
p.xaxis.axis_label = 'Day'
p.xaxis.axis_label_text_font_style = 'normal'
p.xaxis.axis_label_text_font_size = '12pt'
现在,我们将编写javascript回调函数,它将通过对整个
ColumnDataSource
应用过滤器来更改
vbar
中使用的
ColumnDataSource
。将此添加到滑块回调中,我们有一个基于javascript的数据过滤器-

callback = CustomJS(args=dict(source=Overall, sc=Curr), code="""       
        var f = slider.value;
        sc.data['x'] = [];
        sc.data['top'] = [];
        for (var i = 0; i <= source.get_length(); i++){
          if (source.data['month'][i] == f){
            sc.data['day'].push(source.data['day'][i])
            sc.data['Sales'].push(source.data['Sales'][i])
          }
        }
        sc.change.emit();
    """)
slider = Slider(start=1, end=12, value=1, step=1, title="Month", callback=callback)
callback.args["slider"] = slider

layout = column(slider, p)

output_file("Filterdata.html")
#fig.view.filters[0].booleans = indices
show(layout)
callback=CustomJS(args=dict(source=total,sc=Curr),code=”“”
var f=滑块值;
sc.data['x']=[];
sc.data['top']=[];
对于(var i=0;i而言,这一方法有效

    callback = CustomJS(args=dict(source=Overall, sc=Curr), code="""       
    var f = slider.value;
    sc.data['day'] = [];
    sc.data['ExtendedPrice'] = [];
    for (var i = 0; i <= source.get_length(); i++){
      if (source.data['month'][i] == f){

        sc.data['day'].push(source.data['day'][i])
        sc.data['ExtendedPrice'].push(source.data['ExtendedPrice'][i])
      }
    }
    sc.change.emit();
""")
callback=CustomJS(args=dict(source=total,sc=Curr),code=”“”
var f=滑块值;
sc.data['天]=[];
sc.data['ExtendedPrice']=[];

对于(var i=0;i Hi Aritesh,非常感谢您的时间。我能够实现此逻辑。但是,我的按天计算的销售数据不正确。但是,月份=1的数据显示正确。其余月份的数据不正确。我想,CustomJava脚本中读取每日销售的循环函数不正确,请验证此l再次感谢您的时间。嗨,Aritesh,我确实再次检查了代码。我发现,天中的旧数据不会被替换。它保持不变,新数据不会被推送。循环似乎是正确的。您有没有想法在用新数据替换前删除天数据?提前感谢这对我有用这是一个小小的调整。在CustomJs中,我指的是X和TOP,而不是day和TOPSales@trinathreddy,没错,我在answerHi aritesh中进行了编辑,还有一点疑问。我们需要在sahrepoint上集成这些绘图。这就是原因,我选择CustomJs。我听说,使用bokeh服务器不允许我们在sh上集成绘图这是正确的吗?或者,我非常乐意使用本机回调函数。