【问题标题】:How to draw categorical bar plot using vbar method in Bokeh plotting module如何在 Bokeh 绘图模块中使用 vbar 方法绘制分类条形图
【发布时间】:2017-06-12 03:52:38
【问题描述】:

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

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

我从历史中发现了几个类似的问题和答案,但它们似乎仍然不能完全解决我的问题。

我尝试了以下代码 sn-p 但失败并出现一些错误:

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。

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

谢谢

【问题讨论】:

    标签: python pandas plot bokeh


    【解决方案1】:

    创建绘图时,您需要定义绘图将采用 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'])
    

    【讨论】:

    • 谢谢,但它不起作用。错误已经消失,但结果是 x 轴采用数值 (1,2,3) 而不是 'A','B','C。
    • @Royalblue 查看我新编辑的答案。它应该可以完全解决您的问题。
    猜你喜欢
    • 2019-07-29
    • 2018-01-06
    • 2021-11-25
    • 2017-07-07
    • 1970-01-01
    • 2017-08-27
    • 2015-10-09
    • 2012-10-23
    相关资源
    最近更新 更多