【问题标题】:Getting the desired datetime value from x axis in bokeh从散景中的 x 轴获取所需的日期时间值
【发布时间】:2016-07-26 19:54:28
【问题描述】:

我已经阅读了文档并在 Google 和 StackOverflow 上搜索了答案,但还没有一个更明智的答案。

我有一个散景图,其中有两个变量“分数”和“压力”的圆形字形,第三个变量“日期”作为日期时间 x 轴(图片 here)。我希望用户能够单击圆圈并被带到一个 URL,该 URL 显示了该特定数据点的详细视图,该特定数据点由其相应的日期标识。

我启用了一个带有 openURL 回调的点击工具,它在 URL 的末尾附加了日期时间值。问题在于,一旦单击数据点,传递的日期时间值就不是所需的格式:'2016-07-20'。我得到的是以下值:'1468969200000'。因此,用户被重定向到“url/1468969200000/”而不是“url/2016-07-20/”。

有没有办法更改单击数据点后传递的日期值的格式?

这是我的代码(在 jupyter notebook 中运行):

import datetime
from bokeh.plotting import figure, output_notebook, show
from bokeh.models import Range1d, OpenURL, TapTool, HoverTool, ColumnDataSource, DatetimeTickFormatter

data = {'score': [4.33, 2.66, 4.66, 2.66, 2.66, 1.66, 1.0, 4.33], 
        'stress': [3.66, 3.0, 3.0, 1.33, 3.66, 3.33, 1.0, 4.33], 
        'date': [
            datetime.date(2016, 7, 17), 
            datetime.date(2016, 7, 18), 
            datetime.date(2016, 7, 19), 
            datetime.date(2016, 7, 20), 
            datetime.date(2016, 7, 21), 
            datetime.date(2016, 7, 22), 
            datetime.date(2016, 7, 23), 
            datetime.date(2016, 7, 24)
        ]
       }

source = ColumnDataSource(data=data)

TOOLS = ['hover', 'pan', 'tap']

plot = figure(x_axis_type='datetime', plot_height=250, tools=TOOLS)

plot.circle('date', 'score', legend='score', size=15, color='red', source=source)
plot.circle('date', 'stress', legend='stress', size=10, color='orange', source=source)
plot.y_range = Range1d(1, 5, bounds=(1,5))
plot.x_range = Range1d(datetime.date(2016, 7, 17), datetime.date(2016, 7, 23))

hover = plot.select(type=HoverTool)
hover.tooltips = [
    ("score", "@score"),
    ("stress", "@stress"),
    ("date", "@date")
    ]

url = 'url/@date/'
taptool = plot.select(type=TapTool)
taptool.callback = OpenURL(url=url)

show(plot)

【问题讨论】:

  • 你有没有想过如何直接解析数字格式的日期时间?我在使用 CrosshairTool 和日期时间轴时遇到了同样的问题,其中以下答案中的解决方法不适用。
  • 当时 jlarsch 建议的解决方案对我有用。从那以后我就没有和 Pandas 合作过,所以再也没有遇到过这个问题。

标签: python datetime bokeh


【解决方案1】:

一个简单的解决方法是另外提供字符串格式的日期。

dateStr= {'dateStr': [x.isoformat() for x in data['date']]}
data.update(dateStr)

然后,您可以在 hover.tooltips 中使用 dateStr 并生成 url

hover.tooltips = [
    ("score", "@score"),
    ("stress", "@stress"),
    ("date", "@dateStr")
    ]

url = 'url/@dateStr/'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2018-06-10
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多