使用散景绘制图形时,如何在x_axis类型为datetime时删除缺少的日期,

时间:2017-08-26 09:11:30

标签: datetime bokeh

我最近尝试使用散景绘制股票数据,绘制的数据是大熊猫的数据框,如

         date  value
0  2017-01-01     10
1  2017-01-02     20
2  2017-01-03     15
3  2017-01-06     30
4  2017-01-07     25

由于周六和周日没有交易,因此此数据框中没有记录。所以这是我画的图像 enter image description here

有没有办法删除这两个空格键? 我的代码在这里:

import pandas as pd
from bokeh.plotting import figure
from bokeh.io import show


df = pd.DataFrame({"date":['2017-01-01','2017-01-02','2017-01-03','2017-01-06','2017-01-07']})
df["value"] = [10,20,15,30,25]
print(df)
width = 24*60*60*100
TOOLS = 'hover,crosshair,pan,wheel_zoom,box_zoom,reset,save,box_select'
picture = figure(width=1000, height=400, tools=TOOLS, x_axis_type='datetime')
picture.vbar(pd.to_datetime(df.date), width,df['value'],0, color='blue', alpha=0.5)
show(picture)

我试图搜索解决方案但是失败了。 How do I make bokeh omit missing dates when using datetime as x-axis

使用索引绘图,然后更改x_axis标签。 但失败了。

我发现在散景的例子中,它也存在这个问题。 http://bokeh.pydata.org/en/0.12.6/docs/gallery/candlestick.html

是否有任何优雅方式来绘制无空间图? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

从Bokeh 0.12.6开始,您可以为轴上的主刻度标签指定覆盖。

import pandas as pd

from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.sampledata.stocks import MSFT

df = pd.DataFrame(MSFT)[:50]
inc = df.close > df.open
dec = df.open > df.close

p = figure(plot_width=1000, title="MSFT Candlestick with Custom X-Axis")

# map dataframe indices to date strings and use as label overrides
p.xaxis.major_label_overrides = {
    i: date.strftime('%b %d') for i, date in enumerate(pd.to_datetime(df["date"]))
}

# use the *indices* for x-axis coordinates, overrides will print better labels
p.segment(df.index, df.high, df.index, df.low, color="black")
p.vbar(df.index[inc], 0.5, df.open[inc], df.close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(df.index[dec], 0.5, df.open[dec], df.close[dec], fill_color="#F2583E", line_color="black")

output_file("custom_datetime_axis.html", title="custom_datetime_axis.py example")

show(p)

enter image description here

如果您的日期非常多,则此方法可能会变得难以操作,并且可能需要Custom Extension

相关问题