数据帧交互绘图:下拉菜单选择要显示的列(Bokeh)

2024-10-01 15:34:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次尝试使用Bokeh库,但我发现文档并不那么简单。在

我有一个数据帧:

A   B   C
1   4   6
2   3   5
3   2   4
4   1   3

我想用Boken创建一个直方图,其中集成了一个小部件,以便用户选择要显示的列(a B或C)。在

我写了以下内容:

^{pr2}$

所以现在我需要将绘图与小部件连接起来。在

我试过下面的方法,但似乎不管用。在

hist = Histogram(df, values={'Field'}, title={'Field'}, plot_width=400)

任何其他不使用bokeh库的解决方案都是受欢迎的,我用Spyder编辑器运行代码,并使用IE可视化结果。在


Tags: 数据方法用户文档绘图fielddf部件
2条回答

所以我还是没能使用bokeh和回调函数以及dataframe。不过,我找到了一个非常简单的选择,当我和朱庇特一起工作时

import matplotlib.pyplot as pl
hue = ["A", "B"]
@interact (col= ["A", "B", "C"])
def plot(col):
    pl.figure()
    pl.hist( df[col]) 
    pl.show()

plot(col)

使用此代码,您将能够与列交互。我用的是最新版本的熊猫,纽比和博克。在新更新中博克图表已弃用。在

import pandas as pd
import numpy as np

#Pandas version 0.22.0
#Bokeh version 0.12.10
#Numpy version 1.12.1

from bokeh.io import output_file, show,curdoc
from bokeh.models import Quad
from bokeh.layouts import row, layout,widgetbox
from bokeh.models.widgets import Select,MultiSelect
from bokeh.plotting import ColumnDataSource,Figure,reset_output,gridplot

d= {'A': [1,1,1,2,2,3,4,4,4,4,4], 'B': [1,2,2,2,3,3,4,5,6,6,6], 'C' : [2,2,2,2,2,3,4,5,6,6,6]}
df = pd.DataFrame(data=d)
names = ["A","B", "C"]

#Since bokeh.charts are deprecated so using the new method using numpy histogram
hist,edge = np.histogram(df['A'],bins=4)
#This is the method you need to pass the histogram objects to source data here it takes edge values for each bin start and end and hist gives count.
source = ColumnDataSource(data={'hist': hist, 'edges_rt': edge[1:], 'edges_lt':edge[:-1]})

plot = Figure(plot_height = 300,plot_width = 400)
#The quad is used to display the histogram using bokeh.
plot.quad(top='hist', bottom=0, left='edges_lt', right='edges_rt',fill_color="#036564", 
          line_color="#033649",source = source)

#When you change the selection it will this function and changes the source data so that values are updated.
def callback_menu(attr, old, new):

    hist,edge = np.histogram(df[menu.value],bins=4)
    source.data={'hist': hist,'edges_rt': edge[1:], 'edges_lt': edge[:-1]}

#These are interacting tools in the final graph
menu = MultiSelect(options=names,value= ['A','B'], title='Sensor Data')
menu.on_change('value', callback_menu)
layout = gridplot([[widgetbox(menu),plot]])
curdoc().add_root(layout)

保存文件后,在同一目录中的Anaconda提示符中使用以下命令启动bokeh服务器,以便可以与图形交互。在

^{pr2}$

运行图形并选择如下所示 Output

相关问题 更多 >

    热门问题