Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python hexbin plot with 2D function

I’m trying to display a two dimensional function on a hexagonal grid with pyplot.hexbin but it only produces a line and ignores the rest of the function. How do I solve this?

def func(x,y):
    return x*2+y*2

x = np.linspace((-0.5)/4*5, (0.5)/4*5, int(2e3))   
y = np.linspace(-0.5, 0.5, int(2e3))    

plt.hexbin(x,
           y,
           func(x,y), 
           gridsize=(8,4),
           cmap='gnuplot')
plt.show()

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The func(x,y) function returns a scalar value for each (x, y) pair, but hexbin expects x and y to be arrays of the same length representing coordinates. Input another array Z with the scalar values which will be the colours of each hex.
Try:

import numpy as np
import matplotlib.pyplot as plt

def func(x,y):
    return x*2+y*2

x = np.linspace((-0.5) / 4 * 5, (0.5) / 4 * 5, int(2e3))
y = np.linspace(-0.5, 0.5, int(2e3))
X, Y = np.meshgrid(x, y)

# Evaluate the function for each combination of x and y
Z = func(X, Y)

plt.hexbin(X.flatten(),    # Flatten X and Y to 1D arrays
           Y.flatten(),
           C=Z.flatten(),  # Flatten Z to 1D array for color values
           gridsize=(8, 4),
           cmap='gnuplot')

plt.show()

You can also add a colorbar before the show like:

plt.colorbar(label='Function Value')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading