Search code examples
pythonmatplotlibhexdifferencebins

How to create a difference map between two matplotlib hexbin maps?


I encountered a problem on creating a difference map between two matplotlib.pyplot hexbin plots, which means to get the value differences of each corresponding hexbin first and then create a difference hexbin map.

To give a simple example of my problem here, say the value of one hexbin in Map 1 is 3 and the value of the corresponding hexbin in Map 2 is 2, what I would like to do is to get the difference 3 – 2 = 1 first and then plot it in a new hexbin map, i.e. a difference map, at the same positions as Map 1 and Map 2.

My input codes and output plots are as follows. Could anyone please give me a solution to this problem?

Thanks for your time!

In [1]: plt.hexbin(lon_origin_df, lat_origin_df)
Out[1]: <matplotlib.collections.PolyCollection at 0x13ff40610>

enter image description here

In [2]: plt.hexbin(lon_termination_df, lat_termination_df)
Out[2]: <matplotlib.collections.PolyCollection at 0x13fff49d0>

enter image description here


Solution

  • It's possible to get the values from a h=hexbin() using h.get_values(), and set the values using h.set_values(), so you could create a new hexbin and set its values to the difference between the other two. For example:

    import numpy as np
    import matplotlib.pylab as pl
    
    x  = np.random.random(200)
    y1 = np.random.random(200)
    y2 = np.random.random(200)
    
    pl.figure()
    pl.subplot(131)
    h1=pl.hexbin(x, y1, gridsize=3, vmin=0, vmax=40, cmap=pl.cm.RdBu_r)
    pl.colorbar()
    
    pl.subplot(132)
    h2=pl.hexbin(x, y2, gridsize=3, vmin=0, vmax=40, cmap=pl.cm.RdBu_r)
    pl.colorbar()
    
    pl.subplot(133)
    # Create dummy hexbin using whatever data..:
    h3=pl.hexbin(x, y2, gridsize=3, vmin=-10, vmax=10, cmap=pl.cm.RdBu_r)
    h3.set_array(h1.get_array()-h2.get_array())
    pl.colorbar()
    

    enter image description here