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)
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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With