Search code examples
pythonmatplotlibimshow

matplotlib imshow -- use any vector as axis


I would like to use any vector as an axis in plt.imshow().

A = np.random.rand(4, 4)
x = np.array([1, 2, 3, 8])
y = np.array([-1, 0, 2, 3])

I imagine something like this:

plt.imshow(a, x_ax=x, y_ax=y)

I know there is an extent parameter available, but sadly it does not allow for non-equally spaced vectors.

Can anyone please help? Thanks in advance.


Solution

  • Imshow plots are always equally spaced. The question would be if you want to have
    (a) an equally spaced plot with unequally spaced labels, or
    (b) an unequally spaced plot with labels to scale.

    (a) equally spaced plot

    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.random.rand(4, 4)
    x = np.array([1, 2, 3, 8])
    y = np.array([-1, 0, 2, 3])
    
    plt.imshow(a)
    plt.xticks(range(len(x)), x)
    plt.yticks(range(len(y)), y)
    plt.show()
    

    enter image description here

    (b) unequally spaced plot

    import numpy as np
    import matplotlib.pyplot as plt
    
    a = np.random.rand(3, 3)
    x = np.array([1, 2, 3, 8])
    y = np.array([-1, 0, 2, 3])
    X,Y = np.meshgrid(x,y)
    
    plt.pcolormesh(X,Y,a)
    
    plt.xticks(x)
    plt.yticks(y)
    plt.show()
    

    enter image description here

    Note that in this case the "vector" would specify the edges of the grid, thus they would only allow for a 3x3 array.