Python 如何将 x 轴设置为散景图上的日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33869292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:08:09  来源:igfitidea点击:

How can I set the x-axis as datetimes on a bokeh plot?

pythonpandasipython-notebookbokeh

提问by Wilfred Hughes

I'm using bokeh with an ipython notebook.

我在 ipython 笔记本上使用散景。

I want to plot a line graph in bokeh using a pandas DataFrame containing datetimes:

我想使用包含日期时间的 Pandas DataFrame 在散景中绘制折线图:

import pandas as pd
from datetime import datetime as dt
from bokeh.io import output_notebook
from bokeh.charts import Bar, Line, show

df = pd.DataFrame(data=[1,2,3],
                  index=[dt(2015, 1, 1), dt(2015, 1, 2), dt(2015, 1, 3)],
                  columns=['foo'])

output_notebook()
show(Line(df))

However, bokeh uses microseconds! Why is this? How do I fix it?

但是,散景使用微秒!为什么是这样?我如何解决它?

bokeh plot of line

线的散景图

回答by euri10

is that ok ?

这可以吗 ?

enter image description here

在此处输入图片说明

import pandas as pd
from math import pi
from datetime import datetime as dt
from bokeh.io import output_file
from bokeh.charts import show
from bokeh.models import DatetimeTickFormatter
from bokeh.plotting import figure

df = pd.DataFrame(data=[1,2,3],
                  index=[dt(2015, 1, 1), dt(2015, 1, 2), dt(2015, 1, 3)],
                  columns=['foo'])
p = figure(plot_width=400, plot_height=400)
p.line(df.index, df['foo'])
p.xaxis.formatter=DatetimeTickFormatter(
        hours=["%d %B %Y"],
        days=["%d %B %Y"],
        months=["%d %B %Y"],
        years=["%d %B %Y"],
    )
p.xaxis.major_label_orientation = pi/4
output_file('myplot.html')
show(p)

回答by jsignell

FWIW, the default behavior has changed since the question was first posted. The original code now yields:

FWIW,自问题首次发布以来,默认行为已更改。原始代码现在产生:

outcome from code

代码的结果

回答by Emmanuel

As of bokeh 0.12.3, you can now do:

从散景 0.12.3 开始,您现在可以执行以下操作:

p = figure(..., x_axis_type='datetime', ...)