首页 > 解决方案 > Python Bokeh:在缩放时将 X 轴重新启动为 0

问题描述

我在下面的代码创建了一个简单的 xy 线图。

当我放大时,我希望 x 轴代码再次从 0 开始,而不是 3.9/无论缩放的 x 点在图像中是什么。

无缩放:

在此处输入图像描述

缩放后:

在此处输入图像描述

我怎么做?

代码:

from bokeh.io import output_file, show, save
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

data = []
x = list(range(11))
y0 = x
y1 = [10 - xx for xx in x]
y2 = [abs(xx - 5) for xx in x]
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1, y2=y2))
for i in range(3):
    p = figure(title="Title " + str(i), plot_width=300, plot_height=300)
    if len(data):
        p.x_range = data[0].x_range
        p.y_range = data[0].y_range

    p.circle('x', 'y0', size=10, color="navy", alpha=0.5, legend_label='line1', source=source)

    p.legend.location = 'top_right'
    p.legend.click_policy = "hide"
    data.append(p)
plot_col = column(data)
# show the results
show(plot_col)

标签: pythonbokeh

解决方案


这是一个不寻常的要求,没有一个内置的东西会以这种方式运行。如果放大到区间[4,7],范围将更新[4, 7],因此轴将显示[4, 7]的标签。如果只需显示不同的刻度标签就足够了,即使基础范围开始/结束保持其通常的值,那么您可以使用自定义扩展来生成您想要的任何自定义标签。用户指南中有一个示例已经几乎完全符合您的要求:

https://docs.bokeh.org/en/latest/docs/user_guide/extensions_gallery/ticking.html#userguide-extensions-examples-ticking

您还可以使用FuncTickFormatter, 例如(未经测试)做一些更简单的事情

p.xaxis.formatter = FuncTickFormatter(code="""
    return tick - ticks[0]
""")

推荐阅读