【问题标题】:select and update pandas dataframe columns in bokeh plot在散景图中选择和更新熊猫数据框列
【发布时间】:2020-05-14 07:56:08
【问题描述】:

我有一个带有几列和一个数字索引的 pandas 数据框,如下所示:

import pandas as pd
df = pd.DataFrame({'2007':[10,20,30,40], 
                   '2008':[90,60,70,40], 
                   '2009':[30,60,70,10], 
                   '2010':[80,50,30,10]})
df.index = [0, 0.5, 1, 1.5]

我可以使用散景绘制此数据集的特定列,代码如下:

from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.io import output_notebook, show
from bokeh.models.tools import HoverTool
from bokeh.models import Select
from bokeh.layouts import column

from bokeh.resources import INLINE

output_notebook(INLINE) 

ds = ColumnDataSource(df)
p = figure(toolbar_location="above", 
           x_axis_type="linear") 

p.line(source=ds, y='index', x='2007')

hover = HoverTool(tooltips=[("y", 
                             "@index"),
                           ])

p.add_tools(hover)

show(p)

我现在正在尝试连接选择器以使用回调在数据框的列之间切换:

handler = CustomJS(args=dict(source=ds), code="""
   // code to update data field
""")

select = Select(title="df-column:", options=list(df.columns))
select.js_on_change('value', handler)

layout = column(select, p)
show(layout)

我不知道如何访问和更新 X 轴(数据字段)上的值。

当然,这是因为我对JS和columndatasource模型缺乏了解。

【问题讨论】:

    标签: python pandas bokeh


    【解决方案1】:

    不要改变数据,改变指向数据的指针:

    import pandas as pd
    
    from bokeh.io import show
    from bokeh.layouts import column
    from bokeh.models import ColumnDataSource, CustomJS
    from bokeh.models import Select
    from bokeh.models.tools import HoverTool
    from bokeh.plotting import figure
    
    df = pd.DataFrame({'2007': [10, 20, 30, 40],
                       '2008': [90, 60, 70, 40],
                       '2009': [30, 60, 70, 10],
                       '2010': [80, 50, 30, 10]},
                      index=[0, 0.5, 1, 1.5])
    ds = ColumnDataSource(df)
    p = figure(toolbar_location="above", x_axis_type="linear")
    p.add_tools(HoverTool(tooltips=[("y", "@index")]))
    
    line_renderer = p.line('2007', 'index', source=ds)
    
    handler = CustomJS(args=dict(line_renderer=line_renderer), code="""
       line_renderer.glyph.x = {field: cb_obj.value};
    """)
    
    select = Select(title="df-column:", options=list(df.columns))
    select.js_on_change('value', handler)
    
    show(column(select, p))
    

    【讨论】:

    • 谢谢,尤金!我刚刚在编辑我的问题时看到了旅游答案,实际上我在这里找到了一个适应你的例子的解决方案:discourse.bokeh.org/t/update-scatter-plot-x-y-or-both/2511/3 - 你的答案很好!
    • 我正在尝试切换到散景服务器,所以我尝试在 python 中做,相当于 JS 回调。你有什么建议吗?我试过这个gist.github.com/epifanio/fb6123ae73dadf10e8fa2ca6a881edd0 但它失败了ValueError
    • 在您的回调中,将ds.data[new] 替换为dict(field=new)
    • 再次感谢@eugene!非常感谢 :) - 作为参考,我用相同方法的两个工作版本(Python+JS 回调)更新了要点
    猜你喜欢
    • 2019-06-29
    • 2023-04-07
    • 2013-02-13
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2023-02-23
    相关资源
    最近更新 更多