Search code examples
matplotlibaxis-labels

imshow: labels as any arbitrary function of the image indices


imshow plots a matrix against its column indices (x axis) and row indices (y axis). I would like the axes labels to not be indices, but an arbitrary function of the indices.

e.g. pitch detection

imshow(A, aspect='auto') where A.shape == (88200,8)

in the x-axis, shows several ticks at about [11000, 22000, ..., 88000] in the y-axis, shows the frequency bin [0,1,2,3,4,5,6,7]

What I want is:

x-axis labeling are normalized from samples to seconds. For a 2 second audio at 44.1kHz sample rate, I want two ticks at [1,2].

y-axis labeling is the pitch as a note. i want the labels in the note of the pitch ['c', 'd', 'e', 'f', 'g', 'a', 'b'].

ideally:

imshow(A, ylabel=lambda i: freqs[i], xlabel=lambda j: j/44100)


Solution

  • You can do this with a combination of Locators and Formatters (doc).

    ax = gca()
    ax.imshow(rand(500,500))
    
    ax.get_xaxis().set_major_formatter(FuncFormatter(lambda x,p :"%.2f"%(x/44100)))
    ax.get_yaxis().set_major_locator(LinearLocator(7))
    ax.get_yaxis().set_major_formatter(FixedFormatter(['c', 'd', 'e', 'f', 'g', 'a', 'b']))
    draw()