如何基于bokeh Python中的下拉窗口小部件的值交互式绘制条形图? [英] How to plot bar graph interactively based on value of dropdown widget in bokeh python?

查看:147
本文介绍了如何基于bokeh Python中的下拉窗口小部件的值交互式绘制条形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制基于下拉控件的条形图的值.

I want to plot the bar graph based value of dropdown widget.

代码

import pandas as pd
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc
from bokeh.charts import Bar, output_file,output_server, show #use output_notebook to visualize it in notebook


df=pd.DataFrame({'item':["item1","item2","item2","item1","item1","item2"],'value':[4,8,3,5,7,2]})

menu = [("item1", "item1"), ("item2", "item2")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)


def function_to_call(attr, old, new):

    df=df[df['item']==dropdown.value]    
    p = Bar(df, title="Bar Chart Example", xlabel='x', ylabel='values', width=400, height=400)
    output_server()    
    show(p)

dropdown.on_change('value', function_to_call)

curdoc().add_root(dropdown)

问题

  1. 即使已经创建了df,我仍收到流动错误"UnboundLocalError:分配前已引用本地变量' df ".
  2. 如何在下拉菜单下方的网页中绘制条形图?解决了1.中的问题后,显示该语法是什么?

推荐答案

对于1.),在分配它之前先引用它.查看方括号内的df['item']==dropdown.value.这是在分配之前 first 发生的.至于为什么这很重要,那就是Python的工作方式.默认情况下,函数中的所有分配都会创建 local 变量.但是在分配之前,只有全局值可用. Python告诉您,它不允许在单个函数中混合使用全局/本地用法.长话短说,在函数内重命名df变量:

For 1.) you are referencing it before assigning it. Look at the df['item']==dropdown.value inside the square brackets. That happens first before the assignment. As to why this matters, that's how Python works. All assignments in a function by default create local variables. But before the assignment, only the global value is available. Python is telling you it won't allow mixed global/local usage in a single function. Long story short, rename the df variable inside the function:

subset = df[df['item']==dropdown.value]    
p = Bar(subset, ...) 

对于2),您需要将内容放置在布局中(例如column).在项目文档和图库中有很多这样的示例.

For 2.) you need to put things in a layout (e.g. a column). There are lots of example of this in the project docs and in the gallery.

这篇关于如何基于bokeh Python中的下拉窗口小部件的值交互式绘制条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆