2017-02-23 126 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就是这样一个简单的解决方案! –