gpt4 book ai didi

python - 如何在 Bokeh 绘图模块中使用 vbar 方法绘制分类条形图

转载 作者:行者123 更新时间:2023-11-30 22:35:37 25 4
gpt4 key购买 nike

我希望在 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'])

关于python - 如何在 Bokeh 绘图模块中使用 vbar 方法绘制分类条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44491172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com