Using months in x axis in bokeh

梦想的初衷 提交于 2019-12-07 09:13:28

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/35611233/using-months-in-x-axis-in-bokeh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!