Hex tiles#

Hex tile glyphs#

Bokeh can plot hexagonal tiles, which you can use to show binned aggregations and more. The hex_tile() method takes a size parameter to define the size of the hex grid and axial coordinates to specify the tiles.

import numpy as np

from bokeh.plotting import figure, show
from bokeh.util.hex import axial_to_cartesian

q = np.array([0,  0, 0, -1, -1,  1, 1])
r = np.array([0, -1, 1,  0,  1, -1, 0])

p = figure(width=400, height=400, toolbar_location=None)
p.grid.visible = False

p.hex_tile(q, r, size=1, fill_color=["firebrick"]*3 + ["navy"]*4,
           line_color="white", alpha=0.5)

x, y = axial_to_cartesian(q, r, 1, "pointytop")

p.text(x, y, text=[f"({q}, {r})" for (q, r) in zip(q, r)],
       text_baseline="middle", text_align="center")

show(p)

Hex binning#

A more practical example below computes counts per bin using the hexbin() function and plots the color mapped counts.

import numpy as np

from bokeh.models import HoverTool
from bokeh.plotting import figure, show

n = 500
x = 2 + 2*np.random.standard_normal(n)
y = 2 + 2*np.random.standard_normal(n)

p = figure(title="Hexbin for 500 points", match_aspect=True,
           tools="wheel_zoom,reset", background_fill_color='#440154')
p.grid.visible = False

r, bins = p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8)

p.circle(x, y, color="white", size=1)

p.add_tools(HoverTool(
    tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")],
    mode="mouse", point_policy="follow_mouse", renderers=[r]
))

show(p)

You can simplify this code by calling the hexbin() method of figure().