Search code examples
pythonmatplotlibplotimshow

Centering Custom y-ticks Imshow


I'm trying to center yaxis tick marks on an imshow image similar to the one here. In the image, each row is a separate "profile" that I've stacked together. I want the tick location to be at the center of each horizontal section, like this (made in Powerpoint).

Here's some working code to make the images above:

import numpy as np
import matplotlib.pyplot as plt
td = [0,1,2,5,10,15,25,66]
N = len(td)
profiles = np.random.randn(N, 501).cumsum(axis=1)
fig, ax = plt.subplots(1,1)
ax.imshow(profiles, interpolation='none', aspect='auto', extent=[0, 500, N-1, 0])
ax.set_yticks(range(N))
plt.show()

Is there an easy way to do this? Let me know how I can clarify my question. If possible, I'd like to learn how to do this with matplotlib.axes (i.e., fig, ax = plt.subplots(1,1)...). Thanks!


Solution

  • You can manually set y ticks and tick labels at 0.5, 1.5 etc. (matplotlib 3.5.0 or above to do this in one call to set_ylabel):

    import numpy as np
    import matplotlib.pyplot as plt
    
    td = [0,1,2,5,10,15,25,66]
    N = len(td)
    profiles = np.random.randn(N, 501).cumsum(axis=1)
    
    fig, ax = plt.subplots()
    ax.imshow(profiles, interpolation='none', aspect='auto', extent=[0, 500, N, 0])
    ax.set_yticks(np.arange(N) + 0.5, [f'{y}' for y in td])
    

    enter image description here