python - 向 Bokeh 堆叠条形图添加交互

标签 python visualization data-visualization bokeh

使用这里的例子

http://docs.bokeh.org/en/latest/docs/gallery/stacked_bar_chart.html

连同此处的交互示例:

http://docs.bokeh.org/en/latest/docs/user_guide/interaction.html#userguide-interaction

似乎让 slider 更改堆叠条形图的可视化应该非常简单。但是,问题是 bokeh.charts 库中的 Bar 对象没有公开条形图中呈现的数据的来源。据我所知,这是因为 charts 模块不维护这些数据。

是否可以使用 Bar 对象进行如上所述的交互。我不知道从哪里获取数据,以便在 slider 移动时更新条形图。我真的不想在每次 slider 移动时都显式地从基元重建整个条形图。

感谢任何帮助。下面列出了我的冰雹玛丽尝试:

from collections import OrderedDict
import pandas as pd
from bokeh.charts import Bar, output_file, show
from bokeh.sampledata.olympics2014 import data
from bokeh.io import vform
from bokeh.models import Callback, ColumnDataSource, Slider
from bokeh.plotting import figure

output_file("callback_bar_graph.html")

df = pd.io.json.json_normalize(data['data'])

# filter by countries with at least one medal and sort
df = df[df['medals.total'] > 0]
df = df.sort("medals.total", ascending=False)

# get the countries and we group the data by medal type
countries = df.abbr.values.tolist()
gold = df['medals.gold'].astype(float).values
silver = df['medals.silver'].astype(float).values
bronze = df['medals.bronze'].astype(float).values

# build a dict containing the grouped data
medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)

# any of the following commented are also alid Bar inputs
medals = pd.DataFrame(medals)

source = ColumnDataSource(data=dict(medals=medals, countries=countries))

bar = Bar(medals, countries, title="Stacked bars", stacked=True)

callback = Callback(args=dict(source=source), code="""
    var data = source.get('data');
    var f = cb_obj.get('value')
    medals = data['medals']
    countries = data['countries']
    for (i = 0; i < medals.bronze.length; i++) {
        medals.bronze[i] = 2*medals.bronze[i]
    }
    source.trigger('change');
""")

slider = Slider(start=-2, end=2, value=1, step=.1,
                title="value", callback=callback)

layout = vform(slider, bar)

show(layout)

最佳答案

答案是回调!

来源:http://docs.bokeh.org/en/latest/docs/user_guide/interaction.html#callbacks-for-widgets

基本上,您需要创建一个包含条形图数据的 ColumnDataSource 对象。然后,您将创建一个回调对象,它将 ColumnDataSource 实例作为参数,并创建 JS 代码,从 slider 交互中获取数据并更新数据实例/触发更改。

如果您无法让它工作,请发布您的代码,我会尽力提供帮助。

关于python - 向 Bokeh 堆叠条形图添加交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30540833/

相关文章:

python - html5lib 的哪个版本是稳定的?

python - 完成对象及其关系并避免在 sqlalchemy 中进行不必要的查询

python - 我不明白为什么我的数据库没有更新新模型

r - 绘制离散数据的直方图

r - 如何显示趋势线的图例?

git - 可视化 git 存储库的进度

charts - WPF Toolkit 图表中具有相同 Y 轴的两个 LineSeries

javascript - 在笛卡尔坐标系中绘制矩形

python - OpenCV 3.1 绘制轮廓 '(-215) npoints > 0'

r - 使用 R - 如何将 2 个气泡图集成到一个图中