简体   繁体   中英

Bokeh autofill datetime axis missing values: how to stop it?

I'm trying to build an interactive plot from a pandas dataframe of financial data. The dataframe index has some gap when market are closed, or during weekends. The problem is that Bokeh always autofill those gaps when I use the dataframe index as xasis, making it visually ugly.

日期时间轴中散景自动填充间隙的示例。

How can I print my data without gaps?

If you insert NaN between sections, Bokeh will not fill the gap:

source = ColumnDataSource(data=dict(x=[1, 2, 3, np.nan, 10, 20], y=[1, 2, 3, np.nan, 3, 4]))
fig = figure(plot_height=250)
fig.line("x", "y", source=source)
show(fig)

the output:

在此输入图像描述

Here is an example from the repo that plots candlesticks without gaps. You will have to use the integer index of the points as your x-axis, then use a custom tick formatter, or tick overrides to display those as the correct dates:

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)[:51]
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"]))
}
p.xaxis.bounds = (0, df.index[-1])
p.x_range.range_padding = 0.05

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM