Search code examples
bokehhistogram2d

histogram2d example for bokeh


Surprisingly nobody took the pain to make an example in the bokeh gallery for 2D histogram plotting

histogram2d of numpy gives the raw material, but would be nice to have an example as it happens for matplotlib

Any idea for a short way to make one?

Following up a proposed answer let me attach a case in which hexbin does not the job because exagons are not a good fit for the job. Also check out matplotlib result.

Of course I am not saying bokeh cannot do this, but it seem not straightfoward. Would be enough to change the hexbin plot into a square bin plot, but quad(left, right, top, bottom, **kwargs) seems not to do this, nor hexbin to have an option to change "tile" shapes.

hexbin enter image description here


Solution

  • You can make something close with relatively few lines of code (comapring with this example from the matplotib gallery). Note bokeh has some examples for hex binning in the gallery here and here. Adapting those and the example provided in the numpy docs you can get the below:

    import numpy as np
    
    from bokeh.plotting import figure, show
    from bokeh.layouts import row
    
    # normal distribution center at x=0 and y=5
    x = np.random.randn(100000)
    y = np.random.randn(100000) + 5
    
    H, xe, ye = np.histogram2d(x, y, bins=100)
    
    # produce an image of the 2d histogram
    p = figure(x_range=(min(xe), max(xe)), y_range=(min(ye), max(ye)), title='Image')
    
    p.image(image=[H], x=xe[0], y=ye[0], dw=xe[-1] - xe[0], dh=ye[-1] - ye[0], palette="Spectral11")
    
    # produce hexbin plot
    p2 = figure(title="Hexbin", match_aspect=True)
    p.grid.visible = False
    
    r, bins = p2.hexbin(x, y, size=0.1, hover_color="pink", hover_alpha=0.8, palette='Spectral11')
    
    show(row(p, p2))
    

    2d histogram with bokeh