博克多重图表链接行为

2024-10-01 22:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张图表。当我放大顶部或底部图表时,x轴都会更新并显示相同的日期范围,这非常好。问题是两个图表上的y轴完全不同,所以当我放大顶部图表时,x&;y轴的刻度相应。在底部图表上,虽然x轴会相应缩放,但y轴不会。我不能使用y_范围=fig.y_范围,因为y范围非常不同

当两个图表的y轴范围不同时,放大顶部图表时,底部图表的y轴是否会相应缩放

更新-我所指的相应更新

假设我的x轴从2020年1月1日到2020年12月31日。现在,假设我使用内置工具在顶部图表上放大2020年7月的整个时间,底部图表的x轴将自动进行相应调整,即,现在在两个图表上放大整个7月的x轴。通过使用直线x_range=fig.x_range,这项工作非常出色。两个图表共享相同的x轴

但是它们的y轴不同,所以我不能使用y_范围=图y_范围

所以我想做的是当我放大顶部图表时&;x&;y轴自动重新缩放。我希望底部图表的y轴也能重新缩放(前面提到的x轴会自动执行此操作)

下面是我的代码

cds = ColumnDataSource(data=df)   

fig = figure(plot_width=W_PLOT, plot_height=H_PLOT, 
             tools=TOOLS,
             x_axis_type="datetime",
             title=name,
             toolbar_location='above')

# lets add a moving average
fig.line(x='time_stamp', y='ma_20', source=cds, legend_label='MA 20')

fig_ind = figure(plot_width=W_PLOT, plot_height=H_PLOT_IND,
                 tools=TOOLS,
                 x_axis_type="datetime",
                 x_range=fig.x_range)

fig_ind.line(x='time_stamp', y='ma_100', source=cds, legend_label='MA 100')

show(gridplot([[fig],[fig_ind]]))

Tags: plot图表figrangewidthtoolsampfigure
1条回答
网友
1楼 · 发布于 2024-10-01 22:44:28

以下是如何在公共X范围内使用CustomJS回调来实现这一点:

from bokeh.models.ranges import DataRange1d
from bokeh.layouts import column
from bokeh.models.sources import ColumnDataSource
from bokeh.models import CustomJS

import pandas as pd
import numpy as np


df = pd.DataFrame(
    {
        'fig1_y': np.linspace(0, 100, 100),
        'fig2_y': np.linspace(0, 1000, 100),
        'common_x': pd.date_range(
            start='2020-01-01',
            end='2021-01-01',
            periods=100
        )
    }
)

cds = ColumnDataSource(data=df)

common_x_range = DataRange1d(bounds='auto')

fig = figure(
    plot_width=500,
    plot_height=200,
    x_axis_type="datetime",
    x_range=common_x_range
)

fig.line(
    x='common_x',
    y='fig1_y',
    source=cds,
    legend_label='MA 20'
)

fig2 = figure(
    plot_width=500,
    plot_height=200,
    x_axis_type="datetime",
    x_range=common_x_range,
    y_range=DataRange1d(bounds='auto')
)

fig2.line(
    x='common_x',
    y='fig2_y',
    source=cds,
    legend_label='MA 100'
)


callback = CustomJS(
    args={
        'y_range': fig2.y_range,
        'source': cds
    }, code='''
    var x_data = source.data.common_x,
        fig2_y = source.data.fig2_y,
        start = cb_obj.start,
        end = cb_obj.end,
        min = Infinity,
        max = -Infinity;

    for (var i=0; i < x_data.length; ++i) {
        if (start <= x_data[i] && x_data[i] <= end) {
            max = Math.max(fig2_y[i], max);
            min = Math.min(fig2_y[i], min);
        }
    }
    
    y_range.start = min
    y_range.end = max
''')
common_x_range.js_on_change('start', callback)
common_x_range.js_on_change('end', callback)

show(column([fig,fig2]))

相关问题 更多 >

    热门问题