Meshgrid Creation in NumPy

NumPy provides the meshgrid() function to generate coordinate matrices from coordinate vectors. This is particularly useful for evaluating functions over a grid.

1. Creating a Basic Meshgrid

The meshgrid() function takes two 1D arrays and produces two 2D coordinate matrices.

    import numpy as np
    
    x = np.array([1, 2, 3])
    y = np.array([4, 5, 6])
    X, Y = np.meshgrid(x, y)
    print("X:\n", X)
    print("Y:\n", Y)
        

Output:

    X:
     [[1 2 3]
      [1 2 3]
      [1 2 3]]
    
    Y:
     [[4 4 4]
      [5 5 5]
      [6 6 6]]
        

2. Visualizing a Meshgrid

Meshgrids are useful for plotting functions over a 2D space.

    import matplotlib.pyplot as plt
    
    Z = X ** 2 + Y ** 2
    plt.contourf(X, Y, Z, cmap='viridis')
    plt.colorbar()
    plt.xlabel('X axis')
    plt.ylabel('Y axis')
    plt.title('Contour Plot of Z = X^2 + Y^2')
    plt.show()
        

Conclusion

The meshgrid() function in NumPy is an essential tool for creating coordinate grids. It is widely used in scientific computing, visualization, and function evaluation over a grid.





Advertisement