Keep a fixed aspect ratio when zooming with box tool

Is that possible to force an equal aspect ratio when zooming using box_zoom ?

The use case is when zooming on an image, you don’t really want to zoom and modify the aspect ratio of the pixel. You want them to stay as a square.

1 Like

Yes you can set plot.match_aspect = True. Note that both the ranges of the plot have to be auto-ranging DataRange1d instances (the default). This is because, if you set fixed range values, Bokeh assumes you know what you want, and honors those setting (i,e. it won’t override your explicit settings in order to adjust the ranges to match the screen aspect)

1 Like

I already tried match_aspect and it does not work. But I guess, I am doing something wrong. Consider the following code:

import numpy as np

import panel as pn; pn.extension()
import bokeh as bk
from bokeh import plotting

image = np.random.random((256, 256))

figure_args = {}
figure_args['tools'] = "pan,wheel_zoom,box_zoom,save,reset"
figure_args['active_scroll'] = "wheel_zoom"
figure_args['match_aspect'] = True
figure_args['sizing_mode'] = 'stretch_both'

fig = plotting.figure(**figure_args)
fig.toolbar.logo = None

color_mapper = bk.models.LinearColorMapper(palette=bk.palettes.Viridis256, low=0, high=1)
fig.image(image=[image], x=[0], y=[0], dw=[256], dh=[256], color_mapper=color_mapper)
color_bar = bk.models.ColorBar(color_mapper=color_mapper, location=(0, 0))

fig.x_range.range_padding = 0
fig.y_range.range_padding = 0


Zooming with the box tool, let you zoom without keeping the aspect ratio and so the pixel end up being deformed.

Sorry, I thought the question was about the wheel zoom. The box zoom tool has its own match_aspect that you will want to set to True, to constrain the boxes that it can draw: BoxZoomTool.match_aspect


That’s what I was looking for. Thanks!