Search code examples
pythonbokeh

Aspect ratio for box_zoom bokeh


I am plotting a map in bokeh to which I havde added tools in my toolbar. However I am having problems with the box_zoom as it allows to zoom in a rectangular which distort the map. How do I fix the aspect ratio of the box_zoom?

I have found this thread but do not understand how to implement it: https://discourse.bokeh.org/t/keep-a-fixed-aspect-ratio-when-zooming-with-box-tool/3580/3

My code is below:

# Create figure object.
p = figure(title = '2000-2020',
           title_location = 'above',
           plot_height = 400 ,
           plot_width = 400, 
           toolbar_location = 'above',
           tools = 'pan, wheel_zoom, box_zoom, reset',
           aspect_scale=0.05)
# Change font size on title

p.title.text_font_size = '12pt'
p.axis.visible = False
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
# Add patch renderer to figure.
neighbourhoods = p.patches('xs','ys', source = geosource,
                   fill_color = {'field' :'trees0020',
                                 'transform' : color_mapper},
                   line_color = 'black', 
                   line_width = 0.75, 
                   fill_alpha = 1)
# Create hover tool
p.add_tools(HoverTool(renderers = [neighbourhoods],
                      tooltips = [('Neighbourhood','@district'),
                                 ('Trees','@trees0020')]))
p.add_layout(color_bar, 'below')
p.toolbar.logo = None
# Remove the grey box around the plot
p.outline_line_color = None

show(p)

Solution

  • Same way you already do it with HoverTool - remove the box_zoom from the tools argument and just call

    from bokeh.models import BoxZoomTool
    
    p.add_tools(BoxZoomTool(match_aspect=True))