2

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

1 Answer 1

4

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'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but it doesnt work. The error has gone but the outcome is that the x axis takes numerical values (1,2,3) rather than 'A','B','C.
@Royalblue See my new edited answer. It should solve your issue completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.