在散景中使用 x 轴上的月份

Using months in x axis in bokeh

假设我有以下数据:

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

我正在使用散景来可视化结果:

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

结果还可以。我想要的是代表一个月的 x 轴(1:一月,2:二月..)。我正在执行以下操作以将数字转换为月份:

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)

结果是空图。以下也不起作用:

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

知道如何通过它吗?

你有两个选择:

您可以使用日期时间轴:

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

并传递 datetime 对象或 unix(自纪元以来的秒数)时间戳值作为 x 值。

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

DatetimeTickFormatter 内容将修改标签的格式(完整的月份名称、数字月份等)。这些文档在这里:

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

第二个:

您可以像

这样使用分类 x 轴
p = figure(x_range=['Jan', 'Feb', 'Mar', ...)

与您的 x_range 相对应的绘图 x 值,例如:

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

用户指南在此处介绍了分类轴:

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

这是一个例子: