示例:当使用datetime作为x轴时,如何使bokeh忽略缺少的日期 [英] Example: how do I make bokeh omit missing dates when using datetime as x-axis

查看:185
本文介绍了示例:当使用datetime作为x轴时,如何使bokeh忽略缺少的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来消除x轴上没有数据(对于散景图)的空间".

I was looking for a way to eliminate the "spaces" in the x-axis where there is no data, this for a bokeh graph.

然后我在这里偶然发现了一个例子: 我如何制作使用datetime作为x轴时,bokeh忽略缺少的日期

Then I stumbled on an example here: How do I make bokeh omit missing dates when using datetime as x-axis

示例:

from math import pi

import pandas as pd

from bokeh.sampledata.stocks import MSFT
from bokeh.plotting import figure, show, output_file
from bokeh.models.formatters import TickFormatter, String, List

# In this custom TickFormatter, xaxis labels are taken from an array of date
# Strings (e.g. ['Sep 01', 'Sep 02', ...]) passed to the date_labels property. 
class DateGapTickFormatter(TickFormatter):
    date_labels = List(String)

    __implementation__ = """
_ = require "underscore"
HasProperties = require "common/has_properties"

class DateGapTickFormatter extends HasProperties
  type: 'DateGapTickFormatter'

  format: (ticks) ->
    date_labels = @get("date_labels")
    return (date_labels[tick] ? "" for tick in ticks)

module.exports =
  Model: DateGapTickFormatter
"""

df = pd.DataFrame(MSFT)[:50]

# xaxis date labels used in the custom TickFormatter
date_labels = [date.strftime('%b %d') for date in pd.to_datetime(df["date"])]

mids = (df.open + df.close)/2
spans = abs(df.close-df.open)

inc = df.close > df.open
dec = df.open > df.close
w = 0.5

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

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

p = figure(tools=TOOLS, plot_width=1000, toolbar_location="left")

# Using the custom TickFormatter. You must always define date_labels
p.xaxis[0].formatter = DateGapTickFormatter(date_labels = date_labels)

# x coordinates must be integers. If for example df.index are 
# datetimes, you should replace them with a integer sequence
p.segment(df.index, df.high, df.index, df.low, color="black")
p.rect(df.index[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black")
p.rect(df.index[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black")

p.title = "MSFT Candlestick with custom x axis"
p.xaxis.major_label_orientation = pi/4

p.grid[0].ticker.desired_num_ticks = 6

show(p)  # open a browser

当我尝试运行它(使用Bokeh 0.11.1)时,总是得到空白的浏览器页面. 我究竟做错了什么?另外,要处理的内容(及其后的内容):实现 =

When I try to run it (with Bokeh 0.11.1), I always get a blank browser page. What am I doing wrong? Also, what's the deal with (and the stuff after): implementation =

更新16/06:

感谢您的快速响应!我尝试使用在"bigreddot"答案中找到的新"实现"来运行它,但浏览器页面仍然空白.使用散景0.11.1.现在我的代码如下:

Thanks for the fast response! I've tried to run it with the new 'implementation' found in 'bigreddot' answer, but I still get a blank browser page. With Bokeh 0.11.1. Now my code looks like:

from math import pi
import pandas as pd

from bokeh.sampledata.stocks import MSFT
from bokeh.plotting import figure, show, output_file
from bokeh.models.formatters import TickFormatter, String, List

# In this custom TickFormatter, xaxis labels are taken from an array of date
# Strings (e.g. ['Sep 01', 'Sep 02', ...]) passed to the date_labels property.
class DateGapTickFormatter(TickFormatter):
    date_labels = List(String)

    __implementation__ = """
    _ = require "underscore"
    Model = require "model"
    p = require "core/properties"

    class DateGapTickFormatter extends Model
      type: 'DateGapTickFormatter'

      doFormat: (ticks) ->
        date_labels = @get("date_labels")
        return (date_labels[tick] ? "" for tick in ticks)

      @define {
        date_labels: [ p.Any ]
      }

    module.exports =
      Model: DateGapTickFormatter
    """

df = pd.DataFrame(MSFT)[:50]

# xaxis date labels used in the custom TickFormatter
date_labels = [date.strftime('%b %d') for date in pd.to_datetime(df["date"])]

mids = (df.open + df.close)/2
spans = abs(df.close-df.open)

inc = df.close > df.open
dec = df.open > df.close
w = 0.5

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

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

p = figure(tools=TOOLS, plot_width=1000, toolbar_location="left")

# Using the custom TickFormatter. You must always define date_labels
p.xaxis[0].formatter = DateGapTickFormatter(date_labels = date_labels)

# x coordinates must be integers. If for example df.index are
# datetimes, you should replace them with a integer sequence
p.segment(df.index, df.high, df.index, df.low, color="black")
p.rect(df.index[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black")
p.rect(df.index[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black")

p.title = "MSFT Candlestick with custom x axis"
p.xaxis.major_label_orientation = pi/4

p.grid[0].ticker.desired_num_ticks = 6

show(p)

我想念什么吗?

推荐答案

更新:通过配置标签替代,可以在最新发行版中更简单地完成此任务,而根本不需要任何JS.这是一个完整的示例:

UPDATE: This task can be accomplished in recent releases much more simply, without any JS at all, by configuring label overrides. Here is a complete example:

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.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")


show(p)

放大其中一个日期间隔:

Zoomed in on one of the date gaps:

这篇关于示例:当使用datetime作为x轴时,如何使bokeh忽略缺少的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆