使用熊猫日期时间索引的散景滑块
问题描述:
我试图通过散景到我的连接到熊猫数据框的情节添加一个滑块。使用熊猫日期时间索引的散景滑块
该图利用日期时间指数显示空气质量指数如何超过一年。
我想补充一个滑块每个月,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")
答
我只是通过我的项目类似的情况工作。我没有使用熊猫日期时间功能,因为我的日期是混合格式,但是一旦我清理了我的数据,就很容易更新。重要的部分是让您的回调函数调整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属性。