Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using months in x axis in bokeh

Tags:

python

bokeh

Lets say I have the following data:

import random
import pandas as pd
numbers = random.sample(range(1,50), 12)
d = {'month': range(1,13),'values':numbers}
df = pd.DataFrame(d)

I am using bokeh to visualize the results:

 p = figure(plot_width=400, plot_height=400)
 p.line(df['month'], df['values'], line_width=2)
 output_file('test.html')
 show(p)

enter image description here

The results are ok. What I want is the x axis to represent a month(1:January,2:February..). I am doing the following to convert the numbers to months:

import datetime
df['month'] = [datetime.date(1900, x, 1).strftime('%B') for x in df['month']]
p = figure(plot_width=400, plot_height=400)
p.line(df['month'], df['values'], line_width=2)
show(p)

The results is an empty figure. The following is also not working:

p.xaxis.formatter = DatetimeTickFormatter(format="%B")

Any idea how to overpass it?

like image 908
Mpizos Dimitris Avatar asked Mar 13 '23 04:03

Mpizos Dimitris


1 Answers

You have two options:

You can use a datetime axis:

p = figure(plot_width=400, plot_height=400, x_axis_type='datetime')

And pass either datetime objects or unix (seconds-since-epoch) timestamps values as x-values.

e.g. df['month'] = [datetime.date(1900, x, 1) for x in df['month']]

The DatetimeTickFormatter stuff will then modify the formatting of labels (full month name, numeric month, etc). Those docs are here:

http://docs.bokeh.org/en/latest/docs/reference/models/formatters.html#bokeh.models.formatters.DatetimeTickFormatter

Second:

You can kind of use a categorical xaxis like

p = figure(x_range=['Jan', 'Feb', 'Mar', ...)

The plot x-values that correspond to your x_range, like:

x = ['Jan', 'Feb', 'Mar', ...]
y = [100, 200, 150, ...]
p.line(x, y)

The user guide covers categorical axes here:

http://docs.bokeh.org/en/latest/docs/user_guide/plotting.html#categorical-axes

Here's an example of that:

Categorical Axis example

like image 111
Luke Canavan Avatar answered Mar 25 '23 04:03

Luke Canavan