python - 散点图上的 Bokeh 图回归线

标签 python regression bokeh scatter-plot

我使用 Python 和 Bokeh 在同一图表中生成了两个散点图,并添加了复选框以允许单独查看散点图。

如何使用 Bokeh 为两个散点图(带方程)添加回归线?

output_file("Scatterplot.html")

#scatter plot
S0 = f.circle(A_area, A_price,
         fill_alpha=0.3, size=3, color='green')
S1 = f.circle(B_area, B_price,
         fill_alpha=0.3, size=3, color='blue')

#widget-checkbox
checkboxes = CheckboxGroup(labels=["A", "B"], active=[0, 1])
callback = CustomJS(code="""S0.visible = false; // same S0 passed in from args
                            S1.visible = false;
                            // cb_obj injected in by the callback
                            if (cb_obj.active.includes(0)){S0.visible = true;} // 0 index box is S0
                            if (cb_obj.active.includes(1)){S1.visible = true;}""",
                    args={'S0': S0, 'S1': S1})

checkboxes.js_on_click(callback)

最佳答案

您使用 numpy 计算直线拟合,然后在 Bokeh 中绘制它:

import numpy as np
from bokeh.plotting import figure
from bokeh.io import show

#the data
x=np.array([0,1,2,3,4,5,6,7,8])
y=np.array([1,2,3,5,4,6,8,7,9])

# determine best fit line
par = np.polyfit(x, y, 1, full=True)
slope=par[0][0]
intercept=par[0][1]
y_predicted = [slope*i + intercept  for i in x]

# plot it
fig=figure()
fig.circle(x,y)
fig.line(x,y_predicted,color='red',legend='y='+str(round(slope,2))+'x+'+str(round(intercept,2)))
show(fig)

enter image description here

关于python - 散点图上的 Bokeh 图回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603873/

相关文章:

bokeh - 如何刷新 Bokeh 文档

python - 当它是一个单独的词时替换一个子串

python - 使 __dict__ 成为一个属性

javascript - 使用平均值、标准开发或回归来填充 Javascript 数组?

r - 使用lapply中的特定列计算多个回归分析

python - Bokeh:如何向图像绘图添加图例和自定义颜色边界?

python - 无法在 AWS Lambda 中显示信息级别日志记录

python - 在抓取时以 Google 支持的形式提交值

r - R语言分段包函数获取直线方程

python - 使用 RangeSlider 更改轴范围