如何使用Python的Bokeh在日期时间轴上添加更多的x轴刻度和标签?

10 投票
1 回答
6058 浏览
提问于 2025-04-18 07:50

我一直在试用Python的Bokeh库,特别是里面的蜡烛图工具,但我一直搞不清楚怎么在我的图表上添加超过5个日期时间的标签或刻度。如果有人能给点建议,我会很感激。以下是我的代码:

from math import pi
import pandas as pd
import pandas.io.data as web
from bokeh.plotting import *


stocks = 'FB'

#######################################################
date_today = time.strftime("%x") 

def get_px(stock, start, end):
    return web.get_data_yahoo(stock, start, end)

x = get_px(stocks, '1/1/2013', date_today)    
######################################################
######## Function Defined ##############################
def dateConvert(df):
    dt = df.index
    df['Date'] = dt
    df.reset_index(drop=True)
    return df

##### transform data for useability #####

df = dateConvert(x)
df = df.reset_index(drop=True)
df = df.sort_index(axis=1)

cols = ['adj_close', 'close', 'date', 'high', 'low', 'open', 'volume']
df.columns = cols

ewma50 = pd.ewma(df.close, span=50)
ewma200 = pd.ewma(df.close, span=200)


#######################################################
##### PLOT CODE #######################################

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

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

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

figure(x_axis_type = "datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave",
       width=1000, name="candlestick")

hold()

segment(df.date, df.high, df.date, df.low, color='black')
rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black")
rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black")

line(df.date, ewma50, color='blue', legend='ewma 50 day')
line(df.date, ewma200, color='red', legend='ewma 200 day')

curplot().title = "FB Candlestick"
xaxis().major_label_orientation = pi/4

grid().grid_line_alpha=0.3
curplot().width=1200

show()

这是生成的图像:

FB多年份蜡烛图

1 个回答

8

首先,感谢你尝试使用Bokeh!关于你的问题,目前你无法指定图表中刻度的数量。这个数量是自动计算的。我在我们的反馈系统中开了一个问题(https://github.com/ContinuumIO/bokeh/issues/665),我们会对此进行改进,以满足你的需求。如果你想的话,可以在评论中参与讨论。

祝好!

撰写回答