0

我是 Stackoverflow 的新手,我正在尝试使用 python 中的 Bokeh 构建蜡烛图。我知道散景文档中有一个示例代码。我试图使用示例代码并重建我的图表。为简单起见,我在下面粘贴了带有任意数据的代码。

我有以下问题:

  1. 我们如何格式化图表以在 x 尺度上具有 YYYY-MM-DD
  2. 谁能解释一下 W 公式。我知道我们将在 m 秒内得到半天。但为什么 ?
  3. 执行代码时,十字星图不显示y 轴悬停日期(即打开和关闭时的含义相同)。(这可能是因为没有 vbar)但是我们如何克服它?

感谢有人可以提供帮助:) 在此处输入图像描述 我的代码如下:

import pandas as pd 
  
# intialise data of lists. 
data = {'Date':['2020-10-10', '2020-10-09', '2020-10-08', '2020-10-07', '2020-10-06', '2020-10-05', '2020-10-04', '2020-10-03'], 
        'open':[20, 21, 19, 18, 30, 10, 15, 18 ], 
        'high':[25, 28, 24, 20, 40, 10, 19, 18 ], 
        'low':[18, 20, 19, 15, 20, 10, 12, 18 ], 
        'close':[32, 18, 15, 20, 30, 15, 8, 20 ] } 
  
# Create DataFrame 
df = pd.DataFrame(data) 

df['Date2']   = pd.to_datetime(df['Date'], errors='coerce')

##graph below 
from math import pi
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource, NumeralTickFormatter, HoverTool, DaysTicker, DatetimeTickFormatter

inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms

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

p = figure(x_axis_type="datetime", tools=TOOLS )

# 1 Pls help how do we code YYYY-MM-DD on the x-scale ? 
p.xaxis.formatter=DatetimeTickFormatter(months = ['%m/%Y', '%b %Y'], years = ['%Y'])

p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.8

# 2 Pls help on explaining the w
p.segment(df.Date2, df.high, df.Date2, df.low, color="black")
p.vbar(df.Date2[inc], w, df.open[inc], df.close[inc], fill_color="#D5E1DD", line_color="black")
p.vbar(df.Date2[dec], w, df.open[dec], df.close[dec], fill_color="#F2583E", line_color="black")

# 3 Pls help on the Hover tool, why single line do not have date displayed, how to we overcome it?
hover_tool = HoverTool(tooltips=[('Date',"@x{%Y-%m-%d}"), ('Close','$y')],
                       formatters={"@x": 'datetime'},)

p.add_tools(hover_tool)

show(p)  # open a browser
4

1 回答 1

0
  1. 添加days=['%Y-%m-%d']DatetimeTickFormatter构造函数。所有格式都记录在这里
  2. 蜡烛在数据中相隔一天。将它们的宽度设为半天只会在它们之间创建一些空间
  3. 该代码分别为每个渲染器创建隐式数据源。这些隐式数据源中的列以渲染器中的参数命名。vbarx参数,所以它的数据源有这样的列。但是segmentx0and x1,所以数据源没有x列,悬停工具不知道从哪里获取@x字段的数据。理想情况下,您应该使用所需的列自己创建数据源,并将它们与列名一起提供给渲染器。此文档部分提供了包含大量示例的更多详细信息:https ://docs.bokeh.org/en/latest/docs/user_guide/data.html

一个小提示 - 您显示$yClose,但这是不正确的。它只是一个坐标,而不是实际的“关闭”值。当您开始使用数据源时,您将能够指定正确的列名。

于 2020-10-25T08:35:47.287 回答