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()
>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')