2017-10-12 101 views
0

我試圖通過散景到我的連接到熊貓數據框的情節添加一個滑塊。使用熊貓日期時間索引的散景滑塊

該圖利用日期時間指數顯示空氣質量指數如何超過一年。

我想補充一個滑塊每個月,1至12月2016 我無法找到與滑塊連接到連接到一個數據幀大熊貓的陰謀代碼一個明顯的例子。請有人幫忙!

我能夠找到下面的代碼,但繪圖是隨機數據生成的。這段代碼的輸出正是我想要做的,但對時間序列數據。

from bokeh.io import output_notebook, show, vform 
from bokeh.plotting import figure, Figure 
from bokeh.models import ColumnDataSource, Slider, CustomJS 
import numpy as np 

output_notebook() 

x = np.sort(np.random.uniform(0, 100, 2000)) 

y = np.sin(x*10) + np.random.normal(scale=0.1, size=2000) 
fig = Figure(plot_height=400, x_range=(0, 2)) 

source = ColumnDataSource(data={"x":x, "y":y}) 

line = fig.line(x="x", y="y", source=source) 
callback = CustomJS(args=dict(x_range=fig.x_range), code=""" 
var start = cb_obj.get("value"); 
x_range.set("start", start); 
x_range.set("end", start+2); 
""") 

slider = Slider(start=0, end=100, step=2, callback=callback) 
show(vform(slider, fig)) 

我也發現使得這類滑塊(如下/ linked here)的源代碼,但我不能確定如何實現它。正如你可以告訴的那樣,我對Bokeh相當陌生。請幫忙!

class DateRangeSlider(AbstractSlider): 
""" Slider-based date range selection widget. """ 

@property 
def value_as_datetime(self): 
    ''' Convenience property to retrieve the value tuple as a tuple of 
    datetime objects. 

    ''' 
    if self.value is None: 
     return None 
    v1, v2 = self.value 
    if isinstance(v1, numbers.Number): 
     d1 = datetime.utcfromtimestamp(v1/1000) 
    else: 
     d1 = v1 
    if isinstance(v2, numbers.Number): 
     d2 = datetime.utcfromtimestamp(v2/1000) 
    else: 
     d2 = v2 
    return d1, d2 

value = Tuple(Date, Date, help=""" 
Initial or selected range. 
""") 

start = Date(help=""" 
The minimum allowable value. 
""") 

end = Date(help=""" 
The maximum allowable value. 
""") 

step = Int(default=1, help=""" 
The step between consecutive values. 
""") 

format = Override(default="%d %b %G") 

回答

0

我只是通過我的項目類似的情況工作。我沒有使用熊貓日期時間功能,因爲我的日期是混合格式,但是一旦我清理了我的數據,就很容易更新。重要的部分是讓您的回調函數調整ColumnDataSource的.data屬性。

在你有的例子中,回調函數是用Javascript編寫的。我使用了Iain示例中的代碼,但我必須爲熊貓數據框做一個小的解決方法。在下面的例子中,數據是一個熊貓數據框的列表。

def callback(attrname, old, new): 
    month = slider.value 
    source.data = ColumnDataSource(data[month]).data 

這將圖形的當前數據替換爲來自不同熊貓數據框的數據。如果像我一樣,所有的數據都在一個數據框中,你也可以做一些熊貓過濾來返回你想要顯示的數據。

data_to_use = data[data['Month'] == month[slider.value]] 

同樣,當我這樣做,我不得不data_to_use轉換爲ColumnDataSource,然後替換源爲我圖的.data屬性。

0

從散景畫廊的Gapminder例子使用這種使用年份,類似的方法應該爲你的數據集的月份工作。由於您只擔心幾個月,因此您不需要使用日期時間索引,只需將其作爲列表。

gapminder

相關問題