如何在散景绘图模块中使用 vbar 方法绘制分类条形图

How to draw categorical bar plot using vbar method in Bokeh plotting module

我想在 Bokeh 绘图中使用 vbar 方法绘制条形图,其中 x 轴采用分类值而不是数值。教程页面 (http://docs.bokeh.org/en/latest/docs/reference/plotting.html) 中提供的示例只有数字 x 轴。

条形图必须可通过小部件更新,因此似乎无法使用 Bar() 但我尝试使用 vbar() 方法,我可以在其中提供源数据。

我从历史上找到了几个类似的问题和答案,但它们似乎并没有完全解决我遇到的问题。

我尝试了以下代码片段,但由于一些错误而失败:

from bokeh.plotting import figure, output_file
from bokeh.io import show
from bokeh.models import ColumnDataSource, ranges
from bokeh.plotting import figure
import pandas as pd

output_file("test_bar_plot.html")

dat = pd.DataFrame([['A',20],['B',20],['C',30]], columns=['category','amount'])

source = ColumnDataSource(dict(x=[],y=[]))

x_label = "Category"
y_label = "Amount"
title = "Test bar plot"

plot = figure(plot_width=600, plot_height=300,
        x_axis_label = x_label,
        y_axis_label = y_label,
        title=title
        )

plot.vbar(source=source,x='x',top='y',bottom=0,width=0.3)

def update():
        source.data = dict(
            x = dat.category,
            y = dat.amount
        )
        plot.x_range = source.data['x']

update()

show(plot)

如果我指定 x_range 作为 figure() 参数似乎可行,但我想做的是能够根据小部件的状态更新分类值,在这种情况下,必须有我可以通过某种机制即时更改 x_range。

如果你能给我一个修复,我将不胜感激。

谢谢

创建绘图时,您需要定义该绘图将采用 x_range 的因数。

plot = figure(plot_width=600, plot_height=300,
              x_axis_label=x_label,
              y_axis_label=y_label,
              title=title,
              x_range=FactorRange(factors=list(dat.category))
              )

然后在您的更新函数中,您可以修改数据并为您的新类别重新定义 x_range。

def update():
        source.data = dict(
            x = dat.category,
            y = dat.amount
        )
        plot.x_range.factors = list(source.data['x'])