使用回调/小部件绘制正态分布以指定范围

时间:2022-04-04 00:46:07

I am trying to plot a normal distribution where you can specify the range. I need to return this as html. I used some code from this example. What do I need to do make the callback work? Now I get list not defined as error when I check the developer-tools in my browser.

我试着画一个正态分布你可以指定范围。我需要将它作为html返回。我使用了这个例子中的一些代码。我需要做什么来让回调工作?现在,当我在浏览器中检查开发工具时,我得到了未定义为错误的列表。

import numpy as np
import scipy.stats

from bokeh.layouts import column
from bokeh.models import CustomJS, Slider
from bokeh.plotting import figure, output_file, show, ColumnDataSource

output_file("slider2.html")
N = 500;a = 0;b = 1
x = list(np.linspace(a, b, N))
z = list(scipy.stats.norm.pdf(x,abs(b-a)/2,abs(b-a)/6))
source = ColumnDataSource(data=dict(x=x,z=z))

plot = figure(plot_width=400, plot_height=400)
plot.line('x', 'z', source=source, line_width=2, line_alpha=0.3)

callback = CustomJS(args=dict(source=source), code="""
    var d2 = source.get('data');
    var b = cb_obj.get('value')
    d2['x'] = list(np.linspace(a, b, N))
    d2['z'] = scipy.stats.norm.pdf(x,abs(b-a)/2,abs(b-a)/6);
    source.change.emit();
""")

slider = Slider(start=1, end=10, value=1, step=.1, title="upper limit", callback=callback)
layout = column(slider, plot)
show(layout)

1 个解决方案

#1


1  

After a some of tinkering, I managed to get the result I was looking for.

经过一番修修补补,我终于得到了我想要的结果。

To summarise the discussion above: CustomJS code must be written in pure Javascript. Therefore using any python functions will cause errors in the html-file. However Javascript functions can be used.

总结上面的讨论:CustomJS代码必须用纯Javascript编写。因此,使用任何python函数都会导致html文件中的错误。但是可以使用Javascript函数。

callback = CustomJS(args=dict(source=source), code="""
   var d2 = source.get('data');
   var b = cb_obj.get('value')
   for (i = 0; i < 1000; i++) {
      x[i]=Math.random()*b
   }
   x.sort(function(a, b){return a - b})
   source.data['x']=x
   z=d2['z']  
   var first=(1/Math.sqrt(2*Math.PI*Math.pow(b/6,2)))
   for (i = 0; i < x.length; i++) {
      z[i] = first*(Math.exp(-Math.pow((x[i]-(b/2))/(b/6),2)));
   }
   source.trigger('change');
""")

#1


1  

After a some of tinkering, I managed to get the result I was looking for.

经过一番修修补补,我终于得到了我想要的结果。

To summarise the discussion above: CustomJS code must be written in pure Javascript. Therefore using any python functions will cause errors in the html-file. However Javascript functions can be used.

总结上面的讨论:CustomJS代码必须用纯Javascript编写。因此,使用任何python函数都会导致html文件中的错误。但是可以使用Javascript函数。

callback = CustomJS(args=dict(source=source), code="""
   var d2 = source.get('data');
   var b = cb_obj.get('value')
   for (i = 0; i < 1000; i++) {
      x[i]=Math.random()*b
   }
   x.sort(function(a, b){return a - b})
   source.data['x']=x
   z=d2['z']  
   var first=(1/Math.sqrt(2*Math.PI*Math.pow(b/6,2)))
   for (i = 0; i < x.length; i++) {
      z[i] = first*(Math.exp(-Math.pow((x[i]-(b/2))/(b/6),2)));
   }
   source.trigger('change');
""")