Search code examples
pythonmatplotlibcontour

Make a contour plot by using three 1D arrays


As the title indicates I would like to make a contour plot by using three 1D arrays. Let's say that

x = np.array([1,2,3])

and

y = np.array([1,2,3])

and

z = np.array([20,21,45])

To do a contourplot in matplotlib i meshed the x and y coordinate as X,Y = meshgrid(x,y) but then the z array must also be a 2D array. How do I then turn z into a 2d array so it can be used?


Solution

  • Your z is wrong. It needs to give the values at every point of the mesh. If z is a function of x and y, calculate z at what I refer to as X_grid below:

    import numpy as np
    import matplotlib.pyplot as plt
    
    def f(x):
        return (x[:,0]**2 + x[:,1]**2)
    
    x = np.array([1,2,3])
    y = np.array([1,2,3])
    xx, yy = np.meshgrid(x, y)
    X_grid = np.c_[ np.ravel(xx), np.ravel(yy) ]
    z = f(X_grid)
    
    z = z.reshape(xx.shape)
    
    plt.contour(xx, yy, z)