Skip to main content
 首页 » 编程设计

python之持续时间的 Bokeh x_axis_type

2025年02月15日14artech

我的 Bokeh 图上的 x 轴表示像 5 秒 这样的持续时间,而不是像 2016-01-01 12:00:00 这样的时间。有没有办法在我的 Bokeh x 轴上适本地渲染刻度?设置 x_axis_type='datetime' 并不完全正确,从下图中 0ms 的重复可以看出:

请您参考如下方法:

在 Bokeh 0.12.6 上,you can use PrintfTickFormatter .

from bokeh.plotting import figure, output_file, show 
from bokeh.models import PrintfTickFormatter 
 
output_file('output.html') 
 
p = figure(plot_width=400, plot_height=400) p.line(x, y, size=1) 
 
# must be applied to the 1st element, not the axis itself  
p.xaxis[0].formatter = PrintfTickFormatter(format="%sms") 
 
show(p) 

您甚至不必设置 x_axis_type='datetime',它甚至可以使用线性轴。

编辑:应用自定义单位格式,例如 ms/s/min,you have to use FuncTickFormatter ,因为目前 Bokeh 无法处理它太复杂了。从 0.12.6 开始有两种使用方法。

首先,通过使用转译器将 Python 函数转换为 Javascript 代码,通过 Flexx (pip install flexx)。它使所有内容都符合 Python 语法,但需要额外的依赖。

from bokeh.plotting import figure, output_file, show 
from bokeh.models import FuncTickFormatter 
 
output_file('output.html') 
 
p = figure(plot_width=400, plot_height=400) p.line(x, y, size=1) 
 
# custom formatter function 
def custom_formatter(): 
    units = [ 
        ('min', 60000.0), 
        ('s', 1000.0), 
        ('ms', 1.0), 
    ] 
    for u in units: 
        if tick >= u[1]: 
            return '{}{}'.format(tick / u[1], u[0]) 
 
 
# must be applied to the 1st element, not the axis itself  
p.xaxis[0].formatter = FuncTickFormatter.from_py_func(custom_formatter) 
 
show(p) 

最后,通过将实际的 Javascript 代码编写为字符串并将其作为参数传递给格式化程序。 Bokeh 是原生的。请记住,您无法控制客户端环境,因此请避免使用纯 vanilla Javascript 以外的任何东西。

from bokeh.plotting import figure, output_file, show 
from bokeh.models import FuncTickFormatter 
 
output_file('output.html') 
 
p = figure(plot_width=400, plot_height=400) p.line(x, y, size=1) 
 
units = [ 
        ('min', 60000.0), 
        ('s', 1000.0), 
        ('ms', 1.0), 
    ] 
 
# must be applied to the 1st element, not the axis itself  
p.xaxis[0].formatter = FuncTickFormatter(code=""" var units = {'min': 
60000.0, 's': 1000.0, 'ms': 1.0}; for (u in units) { 
    if (tick >= units[u]) { 
        return (tick / units[u] + u); 
    } } """) 
 
show(p) 

我觉得这有点烦人,但这就是我为我的应用程序修复轴的方式。我发现需要对名为 tick 的变量进行硬编码是一种糟糕的编程习惯。希望 Bokeh 能在不久的将来提供更好的解决方案。