Royalblue
Royalblue

Reputation: 701

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

I wish to draw a bar plot using vbar method in Bokeh plotting, where x axis takes categorical values rather than numerical ones. The example provided in the tutorial page (http://docs.bokeh.org/en/latest/docs/reference/plotting.html) has only numerical x axis.

The bar plot must be updatable via widget and therefore it seems that Bar() cannot be used but instead I tried using vbar() method, where I can feed source data.

I found several similar questions and answers from the history, but still they don't seem to exactly address the problem I have.

I tried the following code snippet but it failed with some errors:

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)

It seems to work if I specify x_range as the figure() argument, but what I want to do is to be able to update categorical values according to widget's state, in which case, there must be some mechanism by which I can change the x_range on the fly.

I would appreciate if you give me a fix.

Thank you

Upvotes: 2

Views: 2989

Answers (1)

DuCorey
DuCorey

Reputation: 895

When creating the plot, you need to define that the plot will take factors for it's 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))
              )

Then in your update functions you can modify the data and re-define the x_range for your new categories.

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

Upvotes: 4

Related Questions