Search code examples
pythonmatplotlibplotimshow

Change the cell size/width of imshow or similar function


I need the first and last cells to be half the width.

My goal is to get something like this:

enter image description here

But I got this:

enter image description here

My code:

import numpy as np
import matplotlib.pyplot as plt

data = np.array([0.    , 0.2   , 0.4   , 0.6   , 0.8   , 1.    ])
fig, ax = plt.subplots()
matrix = data.reshape(1, -1)
ax.imshow(matrix, cmap='hot')
plt.show()

Is there an option to do this?


Solution

  • As Jody commented, if you only want to clip the outermost cells, a quick shortcut is to change the axes limits:

    ax.set_xlim(0, 5)
    

    But in the more general case, use pcolormesh for custom grids. Define the x and y cell boundaries and plot your matrix on that custom mesh:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.linspace(0, 1, 6)
    matrix = data.reshape(1, -1)
    
    # define cell bounds
    x = [0, 0.5, 1.5, 2.5, 3.5, 4.5, 5]
    y = [-0.5, 0.5]
    
    # plot matrix on custom mesh
    fig, ax = plt.subplots()
    ax.pcolormesh(x, y, matrix, cmap='hot')
    
    # restyle like imshow
    ax.set_aspect('equal')
    ax.invert_yaxis()
    
    plt.show()
    

    Or for a more programmatic way to define the bounds:

    r, c = matrix.shape
    
    x = np.arange(c + 1) - 0.5  # [-0.5  0.5  1.5  2.5  3.5  4.5  5.5]
    x[0] += 0.5                 # [ 0.   0.5  1.5  2.5  3.5  4.5  5.5]
    x[-1] -= 0.5                # [ 0.   0.5  1.5  2.5  3.5  4.5  5. ]
    
    y = np.arange(r + 1) - 0.5  # [-0.5  0.5]