2017-02-23 38 views
4

我試圖根據自己的需要調整brewer示例(http://bokeh.pydata.org/en/latest/docs/gallery/brewer.html)。我想要的一件事是在x軸上有日期。我做了以下:散景修補程序繪製日期爲x軸將刻度向右移動

timesteps = [str(x.date()) for x in pd.date_range('1950-01-01', '1951-07-01', freq='MS')] 
p = figure(x_range=FactorRange(factors=timesteps), y_range=(0, 800)) 
p.xaxis.major_label_orientation = np.pi/4 

作爲前一行顯示

p = figure(x_range=(0, 19), y_range=(0, 800)) 

的日期的適配,但第一日期1950年1月1日位於在x = 1。我怎樣才能把它移到x = 0?我擁有的第一批真實數據點是該日期的,因此應該與該日期一起顯示,而不是在一個月後顯示。

Graphical explanation

+0

不熟悉'bokeh'。但爲什麼將日期時間轉換爲字符串? – Parfait

+0

好問題。可能不是最小工作示例的一部分,但是在代碼後面的某些內容中,我沒有包括它的必要性。 –

回答

1

好吧,如果你有一個字符串作爲你的x軸的列表,那麼顯然是從1開始計數,那麼你必須修改你的X數據的情節可處第1其實,啤酒開始示例(http://bokeh.pydata.org/en/latest/docs/gallery/brewer.html)的範圍爲0到19,因此它有20個數據點,而不是像您的timesteps列表那樣的19個數據點。我修改的情節作爲x輸入:data['x'] = np.arange(1,N+1)從1開始N.並且我增加了一個多一天到您的列表:timesteps = [str(x.date()) for x in pd.date_range('1950-01-01', '1951-08-01', freq='MS')] 下面是完整的代碼:

import numpy as np 
import pandas as pd 

from bokeh.plotting import figure, show, output_file 
from bokeh.palettes import brewer 

N = 20 
categories = ['y' + str(x) for x in range(10)] 
data = {} 
data['x'] = np.arange(1,N+1) 
for cat in categories: 
    data[cat] = np.random.randint(10, 100, size=N) 

df = pd.DataFrame(data) 
df = df.set_index(['x']) 

def stacked(df, categories): 
    areas = dict() 
    last = np.zeros(len(df[categories[0]])) 
    for cat in categories: 
     next = last + df[cat] 
     areas[cat] = np.hstack((last[::-1], next)) 
     last = next 
    return areas 

areas = stacked(df, categories) 

colors = brewer["Spectral"][len(areas)] 

x2 = np.hstack((data['x'][::-1], data['x'])) 


timesteps = [str(x.date()) for x in pd.date_range('1950-01-01', '1951-08-01', freq='MS')] 
p = figure(x_range=bokeh.models.FactorRange(factors=timesteps), y_range=(0, 800)) 

p.grid.minor_grid_line_color = '#eeeeee' 

p.patches([x2] * len(areas), [areas[cat] for cat in categories], 
      color=colors, alpha=0.8, line_color=None) 
p.xaxis.major_label_orientation = np.pi/4 
bokeh.io.show(p) 

這裏是輸出:

enter image description here

UPDATE

您可以從0離開data['x'] = np.arange(0,N)至19,然後用offset=-1FactorRange,即figure(x_range=bokeh.models.FactorRange(factors=timesteps,offset=-1),...

+0

精彩的,offset = -1就是這樣一個簡單的解決方案! –