[英]Using months in x axis in 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)
The results are ok.结果没问题。 What I want is the x axis to represent a month(1:January,2:February..).我想要的是代表一个月的 x 轴(1:1 月,2:2 月 ..)。 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.并将datetime
对象或 unix (seconds-since-epoch) 时间戳值作为 x 值传递。
eg df['month'] = [datetime.date(1900, x, 1) for x in df['month']]
例如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).然后 DatetimeTickFormatter 内容将修改标签的格式(完整月份名称、数字月份等)。 Those docs are here:这些文档在这里:
http://docs.bokeh.org/en/latest/docs/reference/models/formatters.html#bokeh.models.formatters.DatetimeTickFormatter 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您可以使用分类 xaxis 之类的
p = figure(x_range=['Jan', 'Feb', 'Mar', ...)
The plot x-values that correspond to your x_range, like:对应于您的 x_range 的绘图 x 值,例如:
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 http://docs.bokeh.org/en/latest/docs/user_guide/plotting.html#categorical-axes
Here's an example of that:这是一个例子:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.