Search code examples
matplotlibimshow

imshow non unifrom matrix bin size


I am trying to create an image with imshow, but the bins in my matrix are not equal. For example the following matrix

C = [[1,2,2],[2,3,2],[3,2,3]]

is for X = [1,4,8] and for Y = [2,4,9] I know I can just do xticks and yticks, but I want the axis to be equal..This means that I will need the squares which build the imshow to be in different sizes. Is it possible?


Solution

  • This seems like a job for pcolormesh. From When to use imshow over pcolormesh:

    Fundamentally, imshow assumes that all data elements in your array are to be rendered at the same size, whereas pcolormesh/pcolor associates elements of the data array with rectangular elements whose size may vary over the rectangular grid.

    pcolormesh plots a matrix as cells, and take as argument the x and y coordinates of the cells, which allows you to draw each cell in a different size.

    I assume the X and Y of your example data are meant to be the size of the cells. So I converted them in coordinates with:

    xSize=[1,4,9]
    ySize=[2,4,8]
    x=np.append(0,np.cumsum(xSize)) # gives [ 0  1  5 13]
    y=np.append(0,np.cumsum(ySize)) # gives [ 0  2  6 15]
    

    Then if you want a similar behavior as imshow, you need to revert the y axis.

    c=np.array([[1,2,2],[2,3,2],[3,2,3]])
    plt.pcolormesh(x,-y,c)
    

    Which gives us:

    pcolor to replace imshow